﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Atentis.Connection;
using System.Collections.ObjectModel;
using System.Threading;
using System.Data;

namespace Atentis_Connector
{
	/// <summary>
	/// Тип подключения к серверу
	/// </summary>
	public enum AlorConnectionType
	{
		/// <summary>
		/// Стандартное подключение (мониторинг Standard Connection)
		/// </summary>
		ctStandart = 0,
		/// <summary>
		/// Быстрое подключение (боевой режим Fast Connection)
		/// </summary>
		ctFast = 1,
	}

	// Класс объекта типа подключение (Slot в Атентисе)
	class AtentisConnection : IConnection
	{
		#region Переменные

		private Slot m_DataSlot = null;
		private Slot m_TransSlot = null;
		private Slot m_curSlt = null;
		private OrderDatas m_OrderDatas;
		private SecMaster m_SecMaster;
		public SecMaster SecMaster { get { return m_SecMaster; } set { m_SecMaster = value; } }

		private AlorConnectionType m_ConnectionType;

		/// <summary>
		/// Тип подключения к серверу
		/// </summary>
		public AlorConnectionType ConnectionType { get { return m_ConnectionType; } set { m_ConnectionType = value; } }

		#endregion Переменные

		#region Данные_Подключения

		/// <summary>
		/// Аккаунт
		/// </summary>
		public string Account { get { return m_DataSlot.TrdAccID; } }

		/// <summary>
		/// Сслыка счета
		/// </summary>
		public string BrokerRef { get { return m_DataSlot.BrokerRef; } }

		/// <summary>
		/// Тип сервера
		/// </summary>
		public string ServerType { get { return m_DataSlot.ServerType; } }

		private string m_ConnectionID;
		/// <summary>
		/// Идентификатор подлючения
		/// </summary>
		public string ConnectionID { get { return m_ConnectionID; } }

		private string m_Server;
		/// <summary>
		/// Адрес сервера
		/// </summary>
		public string Server { get { return m_Server; } }

		/// <summary>
		/// Логин
		/// </summary>
		public string Login { get { return m_DataSlot.Login; } }

		/// <summary>
		/// Пароль
		/// </summary>
		public string Password { get { return m_DataSlot.Password; } }

		/// <summary>
		/// Порт
		/// </summary>
		public string Port { get { return m_DataSlot.Port.ToString(); } }

		#endregion Данные_Подключения

		#region Таймер_обновлений

		private System.Windows.Forms.Timer m_RefreshTimer;

		private long m_RefreshFreq;
		/// <summary>
		/// Частота обновления таблиц (мс)
		/// </summary>
		public long RefreshFreq
		{
			get { return m_RefreshFreq; }
			set 
			{

				if (value >= 1)
				{
					m_DataSlot.RefreshPeriod = (int)value;
					m_TransSlot.RefreshPeriod = (int)value;
				}

				if (this.ConnectionType == AlorConnectionType.ctFast)
				{
					m_RefreshTimer.Stop();
					m_RefreshFreq = value;
					m_RefreshTimer.Interval = (int)value;
					m_RefreshTimer.Start();
					m_TransSlot.RefreshAllTables();
				}

			}
		}

		#endregion Таймер_обновлений

		#region Инициализационные_таблицы

		//--------------------------------------------------------------------------------
		// Задаем списки требуемых полей таблиц
		private const string fldSec =  "SHORTNAME, SECBOARD, SECCODE, SECNAME, DECIMALS, BID, OFFER, LOW, HIGH, PREVPRICE, OPEN, LAST, NUMTRADES, TIME, STEPPRICE, TRADINGSTATUS, TICKER";
		private const string fldPos  = "CLIENTID, OPENBAL, CURRENTPOS, CBPLIMIT, PLANNEDPOS, LIMIT1, ORDERBUY, ORDERSELL, NETTO, PORTFOLIO, FREE, FREEFORSHORTING, FREEFORMARGIN, FREEFORNONMARGIN, PROFIT";
		private const string fldAT   = "TRADENO, TRADETIME, SECBOARD, SECCODE, PRICE, QUANTITY, VALUE, PERIOD, TRADETYPE";
		private const string fldInd  = "SHORTNAME, NAME, DECIMALS, CURRENTVALUE";

		// Задаем внутреннюю фильтрацию для таблицы финансовых инструментов
		private const string fltEqbr = "SecBoard='EQBR'";

		// Задаем список шаблонов таблиц
		private Table[] openFirstTables = 
		{
			//        Name                 Caption       Param1 Param2 Fields Filter
			new Table("SECURITIES",        "Securities", "",    "",    fldSec,fltEqbr),
			new Table("BOARDS",            "Boards",     "",    "",    "",    ""),
			new Table("INDEXES",           "Indexes",    "",    "",    fldInd,""),
			new Table("NEWS",              "News",       "",    "",    "",    ""),
			new Table("ORDERS",            "Orders",     "",    "",    "",    ""),
			
			//new Table("ORDERBOOK",         "Orderbook",  "",    "",    "",    ""),
			
			new Table("POSITIONS",         "Positions",  "",    "",    fldPos,""),
			new Table("STOPORDERS",        "Stoporders", "",    "",    "",    ""),
			new Table("TRADES",            "Trades",     "",    "",    "",    ""),
			new Table("TRDACC",            "Trdacc",     "",    "",    "",    ""),
			new Table("FIRM_HOLDING_TOTAL","Holding",    "",    "",    "",    ""),

			new Table("TESYSTIME",         "Server Time","",    "",    "",    ""),
			new Table("HISTORY",           "History",    "",    "",    "",    ""),
			new Table("HISTORY_DAILY",     "History_Daily",     "",    "",    "",    ""),
			new Table("ALL_TRADES",        "AllTrd",     "",    "",    fldAT, "" ,   "", "", "", "", DateTime.Now.AddMinutes(-2), DateTime.MaxValue, true)
		};
		/*
		Нужны таблицы:
			+SECURITIES
			+INDEXES
			+NEWS
			+ORDERS
			+ORDERBOOK
			+POSITIONS
			+STOPORDERS
			+TRADES
			+TRDACC
			+FIRM_HOLDING_TOTAL
			+HISTORY
			+HISTORY_DAILY
			+BOARDS
			+TESYSTIME
			+ALL_TRADES
		*/
		/*
		Реализованные классы для таблиц:
			+SECURITIES
			+INDEXES
			+NEWS
			+ORDERS
			+ORDERBOOK
			+POSITIONS
			+STOPORDERS
			+TRADES
			+TRDACC
			+FIRM_HOLDING_TOTAL
			+HISTORY
			+HISTORY_DAILY
			+BOARDS
			+TESYSTIME
			+ALL_TRADES
		*/

		//--------------------------------------------------------------------------------
		
		#endregion Инициализационные_таблицы

		#region Мастер_Финансовых_Инструментов

		private List<ISecurity> m_Securities;
		/// <summary>
		/// Список объектов, типа [Финансовый инструмент]
		/// </summary>
		public List<ISecurity> Securities { get { return m_Securities; } set { m_Securities = value; } }

		#endregion Мастер_Финансовых_Инструментов

		#region Таблицы

		private List<WrapperSecurities> m_WSecurities;
		/// <summary>
		/// Таблица Финанасовых Инструментов
		/// </summary>
		public List<WrapperSecurities> WSerurities { get { return SecMaster.WSerurities; } set { m_WSecurities = value; } }

		private List<WrapperIndexes> m_WIndexes;
		/// <summary>
		/// Таблица Индексов
		/// </summary>
		public List<WrapperIndexes> WIndexes { get { return SecMaster.WIndexes; } set { m_WIndexes = value; } }

		private List<WrapperNews> m_WNews;
		/// <summary>
		/// Таблица Новостей
		/// </summary>
		public List<WrapperNews> WNews { get { return SecMaster.WNews; } set { m_WNews = value; } }

		private List<WrapperOrders> m_WOrders;
		/// <summary>
		/// Таблица Заявок
		/// </summary>
		public List<WrapperOrders> WOrders { get { return SecMaster.WOrders; } set { m_WOrders = value; } }

		private List<WrapperOrderbook> m_WOrderbook;
		/// <summary>
		/// Таблица Стаканов
		/// </summary>
		public List<WrapperOrderbook> WOrderbook { get { return SecMaster.WOrderbook; } set { m_WOrderbook = value; } }

		private List<WrapperPositions> m_WPositions;
		/// <summary>
		/// Таблица Позиций по деньгам
		/// </summary>
		public List<WrapperPositions> WPositions { get { return SecMaster.WPositions; } set { m_WPositions = value; } }

		private List<WrapperStopOrders> m_WStopOrders;
		/// <summary>
		/// Таблица Стоп-Заявок
		/// </summary>
		public List<WrapperStopOrders> WStopOrders { get { return SecMaster.WStopOrders; } set { m_WStopOrders = value; } }

		private List<WrapperTrades> m_WTrades;
		/// <summary>
		/// Таблица Сделок
		/// </summary>
		public List<WrapperTrades> WTrades { get { return SecMaster.WTrades; } set { m_WTrades = value; } }

		private List<WrapperTrdAcc> m_WtrdAcc;
		/// <summary>
		/// Таблица Счетов
		/// </summary>
		public List<WrapperTrdAcc> WtrdAcc { get { return SecMaster.WtrdAcc; } set { m_WtrdAcc = value; } }

		private List<WrapperFirm_Holding_Total> m_WFirm_Holding_Total;
		/// <summary>
		/// Таблица Позиций по бумагам
		/// </summary>
		public List<WrapperFirm_Holding_Total> WFirm_Holding_Total { get { return SecMaster.WFirm_Holding_Total; } set { m_WFirm_Holding_Total = value; } }

		private List<WrapperHistory> m_WHistory;
		/// <summary>
		/// Таблица Истории котировок (минутки)
		/// </summary>
		public List<WrapperHistory> WHistory { get { return SecMaster.WHistory; } set { m_WHistory = value; } }

		private List<WrapperHistory_Daily> m_WHistoryDaily;
		/// <summary>
		/// Таблица Истории котировок (дневки)
		/// </summary>
		public List<WrapperHistory_Daily> WHistoryDaily { get { return SecMaster.WHistoryDaily; } set { m_WHistoryDaily = value; } }

		private List<WrapperBoards> m_WBoards;
		/// <summary>
		/// Таблица Режимов торгов
		/// </summary>
		public List<WrapperBoards> WBoards { get { return SecMaster.WBoards; } set { m_WBoards = value; } }

		private List<WrapperTesystime> m_WTesystime;
		/// <summary>
		/// Таблица Системного времени
		/// </summary>
		public List<WrapperTesystime> WTesystime { get { return SecMaster.WTesystime; } set { m_WTesystime = value; } }

		private List<WrapperAll_Trades> m_WAllTrades;
		/// <summary>
		/// Таблица Всех сделок
		/// </summary>
		public List<WrapperAll_Trades> WAllTrades { get { return SecMaster.WAllTrades; } set { m_WAllTrades = value; } }

		#endregion Таблицы

		#region Конструктор

		/// <summary>
		/// Коструктор
		/// </summary>
		/// <param name="connectionID">Идентификатор подключения</param>
		/// <param name="server">Сервер</param>
		/// <param name="login">Логин</param>
		/// <param name="password">Пароль</param>
		/// <param name="port">Порт (по умолчанию 7800)</param>
		/// <returns>Возвращает слот проинициализированный входными параметрами</returns>
		public AtentisConnection(string connectionID, string server, string login, string password, int port = 7800)
		{
			this.m_RefreshTimer = new System.Windows.Forms.Timer();
			this.m_RefreshTimer.Tick += new EventHandler(this.RefreshTimer_Tick);

			m_DataSlot = new Slot(connectionID, server, port, login, password, false, "", "AlorWrapper", openFirstTables, true);

			m_TransSlot = new Slot(connectionID, server, port, login, password, false, "");

			m_SecMaster = new SecMaster(false);

			m_OrderDatas = new OrderDatas();

		}

		private void RefreshTimer_Tick(object sender, EventArgs e)
		{
			if (this.ConnectionType != null)
			{
				if (this.ConnectionType == AlorConnectionType.ctFast)
					this.m_DataSlot.RefreshAllTables();
			}
		}

		#endregion Конструктор

		#region Методы

		/// <summary>
		/// Подсоединиться
		/// </summary>
		public void Connect()
		{
			if (m_DataSlot == null)
				return;

			m_DataSlot.rqs = new RequestSocket(m_DataSlot);
			SetRSocketEventHandlers(m_DataSlot);
			m_DataSlot.rqs.Init();
			SetSlotEventHandlers(m_DataSlot);
			m_DataSlot.Start();
		}

		#region Обработка_Событий_Слотов

		/// <summary>
		/// Подключение транзакционного слота. происходит после синхронизации слота данных
		/// </summary>
		private void ConnectTransSlot()
		{

			if (m_TransSlot == null)
				return;

			SetSlotEventHandlers(m_TransSlot);
			string resMsg;
			m_TransSlot.OpenConnection(out resMsg);
			RQS_evhLogLine(m_TransSlot, new TableEventArgs(string.Format("FAST CONNECTION: {0}", resMsg)));
		}

		/// <summary>
		/// Добавление обработчиков событий слота
		/// </summary>
		/// <param name="slot">Слот</param>
		private void SetSlotEventHandlers(Slot slot)
		{
			slot.evhSlotStateChanged += new SlotEventHandler(Slot_evhSlotStateChanged);
		}

		/// <summary>
		/// Удаление обработчиков событий слота
		/// </summary>
		/// <param name="slot">Слот</param>
		void removeSlotEventHandlers(Slot slot)
		{
			slot.evhSlotStateChanged -= Slot_evhSlotStateChanged;
		}

		void RQS_evhSynchronized(object sender, TableEventArgs e)
		{
			RQS_evhLogLine(sender, e);
			//Console.WriteLine("[{0:hh:mm:ss}] EVENT: Slot '{1}' synchronized", DateTime.Now, e.RequestSocket.slot.SlotID);
			Thread.Sleep(1000);
			ConnectTransSlot();
			OnConnected(new EventArgs());
		}

		/// <summary>
		/// Добавление обработчиков событий внутренненго объекта RequestSocket
		/// </summary>
		/// <param name="slot">Слот</param>
		private void SetRSocketEventHandlers(Slot slot)
		{
			slot.rqs.evhLoggedIn += RQS_evhServiceLoggedIn;
			slot.rqs.evhNewSession += RQS_evhNewSession;
			slot.rqs.evhNeedNewPassword += RQS_evhNeedNewPassword;
			slot.rqs.evhLogLine += RQS_evhLogLine;
			slot.rqs.evhSynchronized += RQS_evhSynchronized;
		}

		/// <summary>
		/// Удаление обработчиков событий внутренненго объекта RequestSocket
		/// </summary>
		/// <param name="slot">Слот</param>
		void removeRSocketEventHandlers(Slot slot)
		{
			slot.rqs.evhLoggedIn -= RQS_evhServiceLoggedIn;
			slot.rqs.evhNewSession -= RQS_evhNewSession;
			slot.rqs.evhNeedNewPassword -= RQS_evhNeedNewPassword;
			slot.rqs.evhLogLine -= RQS_evhLogLine;
		}


		void RQS_evhLogLine(object sender, TableEventArgs e)
		{
			//Внутренний лог АЛОР-SDK (Atentis)
			Console.WriteLine("[{0:MM/dd/yyyy hh:mm:ss.fff}] LOG: '{1}'", DateTime.Now, e.Message);
		}


		void RQS_evhServiceLoggedIn(object sender, TableEventArgs e)
		{
			//Успешная авторизация на сервере (успешный вход)
			RQS_evhLogLine(sender, e);
			//Console.WriteLine("[{0:hh:mm:ss}] EVENT: LoggedIn", DateTime.Now);
		}

		void Slot_evhSlotStateChanged(object sender, SlotEventArgs e)
		{
			//Изменился статус подключения
			RQS_evhLogLine(sender, new TableEventArgs(e.State.ToString()));
			//Console.WriteLine("[{0:hh:mm:ss}] EVENT: Slot '{1}' state changed, state='{2}'", DateTime.Now, e.Slot.SlotID, e.State.ToString());
			if (e.State == SlotState.Denied)
			{
				//Доступ запрещен (сервер, доступен, но введен неверный логин или пароль)                
			}
			else if (e.State == SlotState.Failed)
			{
				//В случае прихода Failed ничего не делаем, Atentis сам будет пробовать восстановить сессию
			}
			else if (e.State == SlotState.Disconnected)
			{

			}
		}

		void RQS_evhNewSession(object sender, TableEventArgs e)
		{
			//Требуется создание новой сессии. Работа с текущей сессией далее невозможна
			RQS_evhLogLine(sender, e);
			//Console.WriteLine("[{0:hh:mm:ss}] EVENT: New session required", DateTime.Now);
			m_curSlt = (Slot)sender;
			System.Threading.ThreadPool.QueueUserWorkItem(ReconnectSlotAsync, e);
		}

		/// <summary>
		/// Переподключение к серверу «АЛОР-Трейд»
		/// </summary>
		/// <param name="obj">null</param>
		void ReconnectSlotAsync(Object obj)
		{
			Slot slot = m_curSlt;
			if (slot != null)
			{
				System.Threading.Thread.Sleep(1000);
				//Отписываемся от всех событий (обязательно)
				removeSlotEventHandlers(slot);
				removeRSocketEventHandlers(slot);
				//копируем слот
				slot = CloneSlot(slot);
				Connect();
			}
		}


		/// <summary>
		/// Клонирование слота
		/// </summary>
		/// <param name="cslot">Слот, который необходимо клонировать</param>
		/// <returns>Новый слот</returns>
		Slot CloneSlot(Slot cslot)
		{
			Slot newSlot = new Slot();
			newSlot.PublicKeyFile = "";
			newSlot.rqs = new RequestSocket(newSlot);
			newSlot.Server = cslot.Server;
			newSlot.Port = cslot.Port;
			newSlot.Login = cslot.Login;
			newSlot.Password = cslot.Password;
			SetSlotEventHandlers(newSlot);
			SetRSocketEventHandlers(newSlot);
			return newSlot;

		}


		void RQS_evhNeedNewPassword(object sender, TableEventArgs e)
		{
			//Сервер "АЛОР-Трейд" требует ввести новый пароль перед продолжением работы
			//Это требование необходимо проигнорировать, в результате чего придет событие Denied и будет установлен текущий пароль
			//При переподключении связь будет восстановленна
			RQS_evhLogLine(sender, e);
			//Console.WriteLine("[{0:hh:mm:ss}] EVENT: Need new password", DateTime.Now);

		}

		#endregion Обработка_Событий_Слотов

		/// <summary>
		/// Отсоединиться
		/// </summary>
		public void Disconnect()
		{
			if (m_TransSlot != null)
				m_TransSlot.Disconnect();
			if (m_DataSlot != null)
				m_DataSlot.Disconnect();
		}

		/// <summary>
		/// Открытие таблицы
		/// </summary>
		/// <param name="tableName">Имя таблицы из перечисления</param>
		/// <param name="tableFields">Столбцы таблицы</param>
		/// <param name="tableFilter">Фильтр таблицы</param>
		public void OpenTable(WrapperEnums.AllTables tableName, string tableFields, string tableFilter)
		{

			Slot slot = m_DataSlot;
			if (slot != null)
			{
				//Подписываемя на таблицу — tableName
				//Устанавливаем безбазовый режим Baseless = true для всех кроме SECURITIES, который означает, 
				//что таблица tableName не будет сохраняться во внутреннем DataSet-е АЛОР-SDK.
				//Подписываемся на события добавления и обновления строк

				var tName = WrapperEnums.AsString(tableName);

				var x = slot.tables.Find(t => t.Name == tName);
				if (x != null)
				{
					TableEventArgs e = new TableEventArgs("Таблица " + tName + "уже открыта в слоте " + slot.SlotID);
					RQS_evhLogLine(slot, e);
					AddTableToSlot(tName, slot);
				}
				else
				{
					if (tableName == WrapperEnums.AllTables.atORDERBOOK)
					{
						slot.AddOrderbook(tableFields, tableFilter);
					}
					else
					{
						slot.AddTable(new Table(tName, tName, "", "", tableFields, tableFilter));
					}
					AddTableToSlot(tName, slot);
				}
			}
		}
		/// <summary>
		/// Открытие таблицы
		/// </summary>
		/// <param name="tableName">Имя таблицы из перечисления</param>
		/// <param name="secBoard">Код режима торгов</param>
		/// <param name="secCode">Код финансового инстумента</param>
		/// <param name="tableFilter">Фильтр таблицы</param>
		/// <param name="tableSort">Сортировка таблицы</param>
		public void OpenTable(WrapperEnums.AllTables tableName, string secBoard, string secCode, string tableFields, string tableFilter)
		{

			Slot slot = m_DataSlot;
			if (slot != null)
			{
				//Подписываемя на таблицу — tableName
				//Устанавливаем безбазовый режим Baseless = true для всех кроме SECURITIES, который означает, 
				//что таблица tableName не будет сохраняться во внутреннем DataSet-е АЛОР-SDK.
				//Подписываемся на события добавления и обновления строк

				var tName = WrapperEnums.AsString(tableName);

				var x = slot.tables.Find(t => t.Name == tName);

				if (x != null)
				{
					TableEventArgs e = new TableEventArgs("Таблица " + tName + "уже открыта в слоте " + slot.SlotID);
					RQS_evhLogLine(slot, e);
					AddTableToSlot(tName, slot);
				}
				else
				{
					if (tableName == WrapperEnums.AllTables.atORDERBOOK)
					{
						slot.AddOrderbook(secBoard, secCode);
					}
					else
					{
						slot.AddTable(new Table(tName, tName, secBoard, secCode, tableFields, tableFilter));
					}
					AddTableToSlot(tName, slot);
				}
			}
		}

		#region События_и_методы_по_работе_с_таблицами

		private void AddTableToSlot(string tableName, Slot slot)
		{
			var table = slot.LookupTable(tableName, "", ""); //slot.tables.Find(t => t.Name == tableName);
			if (table != null)
			{
				table.Baseless = (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atSECURITIES)) ? false : true;

				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atSECURITIES))
				table.evhAddRow += SECURITIES_AddRowHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atINDEXES))
				table.evhAddRow += INDEXES_AddRowHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atNEWS))
				table.evhAddRow += NEWS_AddRowHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atORDERS))
				table.evhAddRow += ORDERS_AddRowHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atORDERBOOK))
				table.evhAddRow += ORDERBOOK_AddRowHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atPOSITIONS))
				table.evhAddRow += POSITIONS_AddRowHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atSTOPORDERS))
				table.evhAddRow += STOPORDERS_AddRowHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atTRADES))
				table.evhAddRow += TRADES_AddRowHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atTRDACC))
				table.evhAddRow += TRDACC_AddRowHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atFIRM_HOLDING_TOTAL))
				table.evhAddRow += FIRM_HOLDING_TOTAL_AddRowHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atHISTORY))
				table.evhAddRow += HISTORY_AddRowHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atHISTORY_DAILY))
				table.evhAddRow += HISTORY_DAILY_AddRowHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atBOARDS))
				table.evhAddRow += BOARDS_AddRowHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atTESYSTIME))
				table.evhAddRow += TESYSTIME_AddRowHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atALL_TRADES))
				table.evhAddRow += ALL_TRADES_AddRowHandler;

				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atSECURITIES))
				table.evhUpdateRow += SECURITIES_UpdateRowHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atINDEXES))
				table.evhUpdateRow += INDEXES_UpdateRowHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atNEWS))
				table.evhUpdateRow += NEWS_UpdateRowHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atORDERS))
				table.evhUpdateRow += ORDERS_UpdateRowHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atORDERBOOK))
				table.evhUpdateRow += ORDERBOOK_UpdateRowHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atPOSITIONS))
				table.evhUpdateRow += POSITIONS_UpdateRowHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atSTOPORDERS))
				table.evhUpdateRow += STOPORDERS_UpdateRowHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atTRADES))
				table.evhUpdateRow += TRADES_UpdateRowHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atTRDACC))
				table.evhUpdateRow += TRDACC_UpdateRowHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atFIRM_HOLDING_TOTAL))
				table.evhUpdateRow += FIRM_HOLDING_TOTAL_UpdateRowHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atHISTORY))
				table.evhUpdateRow += HISTORY_UpdateRowHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atHISTORY_DAILY))
				table.evhUpdateRow += HISTORY_DAILY_UpdateRowHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atBOARDS))
				table.evhUpdateRow += BOARDS_UpdateRowHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atTESYSTIME))
				table.evhUpdateRow += TESYSTIME_UpdateRowHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atALL_TRADES))
				table.evhUpdateRow += ALL_TRADES_UpdateRowHandler;


				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atSECURITIES))
					table.evhBeginFrame += SECURITIES_BeginFrameHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atINDEXES))
					table.evhBeginFrame += INDEXES_BeginFrameHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atNEWS))
					table.evhBeginFrame += NEWS_BeginFrameHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atORDERS))
					table.evhBeginFrame += ORDERS_BeginFrameHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atORDERBOOK))
					table.evhBeginFrame += ORDERBOOK_BeginFrameHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atPOSITIONS))
					table.evhBeginFrame += POSITIONS_BeginFrameHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atSTOPORDERS))
					table.evhBeginFrame += STOPORDERS_BeginFrameHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atTRADES))
					table.evhBeginFrame += TRADES_BeginFrameHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atTRDACC))
					table.evhBeginFrame += TRDACC_BeginFrameHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atFIRM_HOLDING_TOTAL))
					table.evhBeginFrame += FIRM_HOLDING_TOTAL_BeginFrameHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atHISTORY))
					table.evhBeginFrame += HISTORY_BeginFrameHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atHISTORY_DAILY))
					table.evhBeginFrame += HISTORY_DAILY_BeginFrameHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atBOARDS))
					table.evhBeginFrame += BOARDS_BeginFrameHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atTESYSTIME))
					table.evhBeginFrame += TESYSTIME_BeginFrameHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atALL_TRADES))
					table.evhBeginFrame += ALL_TRADES_BeginFrameHandler;

				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atSECURITIES))
					table.evhEndFrame += SECURITIES_EndFrameHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atINDEXES))
					table.evhEndFrame += INDEXES_EndFrameHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atNEWS))
					table.evhEndFrame += NEWS_EndFrameHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atORDERS))
					table.evhEndFrame += ORDERS_EndFrameHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atORDERBOOK))
					table.evhEndFrame += ORDERBOOK_EndFrameHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atPOSITIONS))
					table.evhEndFrame += POSITIONS_EndFrameHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atSTOPORDERS))
					table.evhEndFrame += STOPORDERS_EndFrameHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atTRADES))
					table.evhEndFrame += TRADES_EndFrameHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atTRDACC))
					table.evhEndFrame += TRDACC_EndFrameHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atFIRM_HOLDING_TOTAL))
					table.evhEndFrame += FIRM_HOLDING_TOTAL_EndFrameHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atHISTORY))
					table.evhEndFrame += HISTORY_EndFrameHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atHISTORY_DAILY))
					table.evhEndFrame += HISTORY_DAILY_EndFrameHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atBOARDS))
					table.evhEndFrame += BOARDS_EndFrameHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atTESYSTIME))
					table.evhEndFrame += TESYSTIME_EndFrameHandler;
				if (tableName == WrapperEnums.AsString(WrapperEnums.AllTables.atALL_TRADES))
					table.evhEndFrame += ALL_TRADES_EndFrameHandler;

			}
		}

		#region ReplBegin

		private void SECURITIES_BeginFrameHandler(object sBeginer, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(SECURITIES_BeginFrameHandler_Async, e);
		}

		private void INDEXES_BeginFrameHandler(object sBeginer, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(INDEXES_BeginFrameHandler_Async, e);
		}

		private void NEWS_BeginFrameHandler(object sBeginer, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(NEWS_BeginFrameHandler_Async, e);
		}

		private void ORDERS_BeginFrameHandler(object sBeginer, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(ORDERS_BeginFrameHandler_Async, e);
		}

		private void ORDERBOOK_BeginFrameHandler(object sBeginer, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(ORDERBOOK_BeginFrameHandler_Async, e);
		}

		private void POSITIONS_BeginFrameHandler(object sBeginer, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(POSITIONS_BeginFrameHandler_Async, e);
		}

		private void STOPORDERS_BeginFrameHandler(object sBeginer, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(STOPORDERS_BeginFrameHandler_Async, e);
		}

		private void TRADES_BeginFrameHandler(object sBeginer, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(TRADES_BeginFrameHandler_Async, e);
		}

		private void TRDACC_BeginFrameHandler(object sBeginer, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(TRDACC_BeginFrameHandler_Async, e);
		}

		private void FIRM_HOLDING_TOTAL_BeginFrameHandler(object sBeginer, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(FIRM_HOLDING_TOTAL_BeginFrameHandler_Async, e);
		}

		private void HISTORY_BeginFrameHandler(object sBeginer, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(HISTORY_BeginFrameHandler_Async, e);
		}

		private void HISTORY_DAILY_BeginFrameHandler(object sBeginer, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(HISTORY_DAILY_BeginFrameHandler_Async, e);
		}

		private void BOARDS_BeginFrameHandler(object sBeginer, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(BOARDS_BeginFrameHandler_Async, e);
		}

		private void TESYSTIME_BeginFrameHandler(object sBeginer, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(TESYSTIME_BeginFrameHandler_Async, e);
		}

		private void ALL_TRADES_BeginFrameHandler(object sBeginer, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(ALL_TRADES_BeginFrameHandler_Async, e);
		}


		private void SECURITIES_BeginFrameHandler_Async(object state)
		{
			m_SecMaster.UpdateSecurities(null, 0, true, false);
		}
		private void INDEXES_BeginFrameHandler_Async(object state)
		{
			m_SecMaster.UpdateIndexes(null, 0, true, false);
		}
		private void NEWS_BeginFrameHandler_Async(object state)
		{
			m_SecMaster.UpdateNews(null, 0, true, false);
		}
		private void ORDERS_BeginFrameHandler_Async(object state)
		{
			m_SecMaster.UpdateOrders(null, 0, true, false);
		}
		private void ORDERBOOK_BeginFrameHandler_Async(object state)
		{
			m_SecMaster.UpdateOrderBook(null, 0, true, false);
		}
		private void POSITIONS_BeginFrameHandler_Async(object state)
		{
			m_SecMaster.UpdatePositions(null, 0, true, false);
		}
		private void STOPORDERS_BeginFrameHandler_Async(object state)
		{
			m_SecMaster.UpdateStoporders(null, 0, true, false);
		}
		private void TRADES_BeginFrameHandler_Async(object state)
		{
			m_SecMaster.UpdateTrades(null, 0, true, false);
		}
		private void TRDACC_BeginFrameHandler_Async(object state)
		{
			m_SecMaster.UpdateTrdacc(null, 0, true, false);
		}
		private void FIRM_HOLDING_TOTAL_BeginFrameHandler_Async(object state)
		{
			m_SecMaster.UpdateHoldings(null, 0, true, false);
		}
		private void HISTORY_BeginFrameHandler_Async(object state)
		{
			m_SecMaster.UpdateHistory(null, 0, true, false);
		}
		private void HISTORY_DAILY_BeginFrameHandler_Async(object state)
		{
			m_SecMaster.UpdateHistory_Daily(null, 0, true, false);
		}
		private void BOARDS_BeginFrameHandler_Async(object state)
		{
			m_SecMaster.UpdateBoards(null, 0, true, false);
		}
		private void TESYSTIME_BeginFrameHandler_Async(object state)
		{
			m_SecMaster.UpdateSystime(null, 0, true, false);
		}
		private void ALL_TRADES_BeginFrameHandler_Async(object state)
		{
			m_SecMaster.UpdateAll_Trades(null, 0, true, false);
		}

		#endregion ReplBegin

		#region ReplEnd

		private void SECURITIES_EndFrameHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(SECURITIES_EndFrameHandler_Async, e);
		}

		private void INDEXES_EndFrameHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(INDEXES_EndFrameHandler_Async, e);
		}

		private void NEWS_EndFrameHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(NEWS_EndFrameHandler_Async, e);
		}

		private void ORDERS_EndFrameHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(ORDERS_EndFrameHandler_Async, e);
		}

		private void ORDERBOOK_EndFrameHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(ORDERBOOK_EndFrameHandler_Async, e);
		}

		private void POSITIONS_EndFrameHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(POSITIONS_EndFrameHandler_Async, e);
		}

		private void STOPORDERS_EndFrameHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(STOPORDERS_EndFrameHandler_Async, e);
		}

		private void TRADES_EndFrameHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(TRADES_EndFrameHandler_Async, e);
		}

		private void TRDACC_EndFrameHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(TRDACC_EndFrameHandler_Async, e);
		}

		private void FIRM_HOLDING_TOTAL_EndFrameHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(FIRM_HOLDING_TOTAL_EndFrameHandler_Async, e);
		}

		private void HISTORY_EndFrameHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(HISTORY_EndFrameHandler_Async, e);
		}

		private void HISTORY_DAILY_EndFrameHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(HISTORY_DAILY_EndFrameHandler_Async, e);
		}

		private void BOARDS_EndFrameHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(BOARDS_EndFrameHandler_Async, e);
		}

		private void TESYSTIME_EndFrameHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(TESYSTIME_EndFrameHandler_Async, e);
		}

		private void ALL_TRADES_EndFrameHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(ALL_TRADES_EndFrameHandler_Async, e);
		}


		private void SECURITIES_EndFrameHandler_Async(object state)
		{
			m_SecMaster.UpdateSecurities(null, 0, false, true);
		}
		private void INDEXES_EndFrameHandler_Async(object state)
		{
			m_SecMaster.UpdateIndexes(null, 0, false, true);
		}
		private void NEWS_EndFrameHandler_Async(object state)
		{
			m_SecMaster.UpdateNews(null, 0, false, true);
		}
		private void ORDERS_EndFrameHandler_Async(object state)
		{
			m_SecMaster.UpdateOrders(null, 0, false, true);
		}
		private void ORDERBOOK_EndFrameHandler_Async(object state)
		{
			m_SecMaster.UpdateOrderBook(null, 0, false, true);
		}
		private void POSITIONS_EndFrameHandler_Async(object state)
		{
			m_SecMaster.UpdatePositions(null, 0, false, true);
		}
		private void STOPORDERS_EndFrameHandler_Async(object state)
		{
			m_SecMaster.UpdateStoporders(null, 0, false, true);
		}
		private void TRADES_EndFrameHandler_Async(object state)
		{
			m_SecMaster.UpdateTrades(null, 0, false, true);
		}
		private void TRDACC_EndFrameHandler_Async(object state)
		{
			m_SecMaster.UpdateTrdacc(null, 0, false, true);
		}
		private void FIRM_HOLDING_TOTAL_EndFrameHandler_Async(object state)
		{
			m_SecMaster.UpdateHoldings(null, 0, false, true);
		}
		private void HISTORY_EndFrameHandler_Async(object state)
		{
			m_SecMaster.UpdateHistory(null, 0, false, true);
		}
		private void HISTORY_DAILY_EndFrameHandler_Async(object state)
		{
			m_SecMaster.UpdateHistory_Daily(null, 0, false, true);
		}
		private void BOARDS_EndFrameHandler_Async(object state)
		{
			m_SecMaster.UpdateBoards(null, 0, false, true);
		}
		private void TESYSTIME_EndFrameHandler_Async(object state)
		{
			m_SecMaster.UpdateSystime(null, 0, false, true);
		}
		private void ALL_TRADES_EndFrameHandler_Async(object state)
		{
			m_SecMaster.UpdateAll_Trades(null, 0, false, true);
		}

		#endregion ReplEnd

		#region Обновление данных

		private void Update_ALL_TRADES(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperAll_Trades();
			try
			{

				foreach (DataColumn c in dr.Table.Columns)
				{
					if (c.ColumnName == "TRADENO") newRow.TradeNo = ((dr["TRADENO"] != DBNull.Value) ? (long)dr["TRADENO"] : 0);
					if (c.ColumnName == "TRADETIME") newRow.TradeTime = ((dr["TRADETIME"] != DBNull.Value) ? (DateTime)dr["TRADETIME"] : DateTime.MinValue);
					if (c.ColumnName == "REPORATE") newRow.RepoRate = ((dr["REPORATE"] != DBNull.Value) ? (double)dr["REPORATE"] : 0);
					if (c.ColumnName == "REPOTERM") newRow.RepoTerm = ((dr["REPOTERM"] != DBNull.Value) ? (int)dr["REPOTERM"] : 0);
					if (c.ColumnName == "STARTDISCOUNT") newRow.StartDiscount = ((dr["STARTDISCOUNT"] != DBNull.Value) ? (double)dr["STARTDISCOUNT"] : 0);
					if (c.ColumnName == "TRADETYPE") newRow.TradeType = ((dr["TRADETYPE"] != DBNull.Value) ? (string)dr["TRADETYPE"] : string.Empty);
					if (c.ColumnName == "SETTLECODE") newRow.SettleCode = ((dr["SETTLECODE"] != DBNull.Value) ? (string)dr["SETTLECODE"] : string.Empty);
					if (c.ColumnName == "SECID") newRow.SecID = ((dr["SECID"] != DBNull.Value) ? (int)dr["SECID"] : 0);
					if (c.ColumnName == "SECBOARD") newRow.SecBoard = ((dr["SECBOARD"] != DBNull.Value) ? (string)dr["SECBOARD"] : string.Empty);
					if (c.ColumnName == "SECCODE") newRow.SecCode = ((dr["SECCODE"] != DBNull.Value) ? (string)dr["SECCODE"] : string.Empty);
					if (c.ColumnName == "PRICE") newRow.Price = ((dr["PRICE"] != DBNull.Value) ? (double)dr["PRICE"] : 0);
					if (c.ColumnName == "QUANTITY") newRow.Quantity = ((dr["QUANTITY"] != DBNull.Value) ? (int)dr["QUANTITY"] : 0);
					if (c.ColumnName == "VALUE") newRow.Value = ((dr["VALUE"] != DBNull.Value) ? (double)dr["VALUE"] : 0);
					if (c.ColumnName == "ACCRUEDINT") newRow.AccruedInt = ((dr["ACCRUEDINT"] != DBNull.Value) ? (double)dr["ACCRUEDINT"] : 0);
					if (c.ColumnName == "YIELD") newRow.Yield = ((dr["YIELD"] != DBNull.Value) ? (double)dr["YIELD"] : 0);
					if (c.ColumnName == "PERIOD") newRow.Period = ((dr["PERIOD"] != DBNull.Value) ? (string)dr["PERIOD"] : string.Empty);
					if (c.ColumnName == "ROWSTATE") newRow.RowState = ((dr["ROWSTATE"] != DBNull.Value) ? (byte)dr["ROWSTATE"] : Convert.ToByte(0));
				}

			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdateAll_Trades(newRow, recId, false, false);
		}


		private void Update_TESYSTIME(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperTesystime();
			try
			{

				foreach (DataColumn c in dr.Table.Columns)
				{
					if (c.ColumnName == "TIME") newRow.Time = ((dr["TIME"] != DBNull.Value) ? (DateTime)dr["TIME"] : DateTime.MinValue);
				}
			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdateSystime(newRow, recId, false, false);
		}

		private void Update_BOARDS(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperBoards();
			try
			{

				foreach (DataColumn c in dr.Table.Columns)
				{
					if (c.ColumnName == "BOARDID") newRow.BoardID = ((dr["BOARDID"] != DBNull.Value) ? (string)dr["BOARDID"] : string.Empty);
					if (c.ColumnName == "BOARDNAME") newRow.BoardName = ((dr["BOARDNAME"] != DBNull.Value) ? (string)dr["BOARDNAME"] : string.Empty);
					if (c.ColumnName == "STATUS") newRow.Status = ((dr["STATUS"] != DBNull.Value) ? (string)dr["STATUS"] : string.Empty);
					if (c.ColumnName == "MARKETID") newRow.MarketID = ((dr["MARKETID"] != DBNull.Value) ? (string)dr["MARKETID"] : string.Empty);
				}
			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdateBoards(newRow, recId, false, false);
		}

		private void Update_HISTORY_DAILY(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperHistory_Daily();
			try
			{

				foreach (DataColumn c in dr.Table.Columns)
				{
					if (c.ColumnName == "RECID") newRow.RecID = ((dr["RECID"] != DBNull.Value) ? (long)dr["RECID"] : 0);
					if (c.ColumnName == "TIME") newRow.Time = ((dr["TIME"] != DBNull.Value) ? (DateTime)dr["TIME"] : DateTime.MinValue);
					if (c.ColumnName == "TICKER") newRow.Ticker = ((dr["TICKER"] != DBNull.Value) ? (string)dr["TICKER"] : string.Empty);
					if (c.ColumnName == "LOW") newRow.Low = ((dr["LOW"] != DBNull.Value) ? (double)dr["LOW"] : 0);
					if (c.ColumnName == "HIGH") newRow.High = ((dr["HIGH"] != DBNull.Value) ? (double)dr["HIGH"] : 0);
					if (c.ColumnName == "OPEN") newRow.Open = ((dr["OPEN"] != DBNull.Value) ? (double)dr["OPEN"] : 0);
					if (c.ColumnName == "CLOSE") newRow.Close = ((dr["CLOSE"] != DBNull.Value) ? (double)dr["CLOSE"] : 0);
					if (c.ColumnName == "VOLUME") newRow.Volume = ((dr["VOLUME"] != DBNull.Value) ? (double)dr["VOLUME"] : 0);

				}
			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdateHistory_Daily(newRow, recId, false, false);
		}

		private void Update_HISTORY(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperHistory();
			try
			{

				foreach (DataColumn c in dr.Table.Columns)
				{
					if (c.ColumnName == "RECID") newRow.RecID = ((dr["RECID"] != DBNull.Value) ? (long)dr["RECID"] : 0);
					if (c.ColumnName == "TIME") newRow.Time = ((dr["TIME"] != DBNull.Value) ? (DateTime)dr["TIME"] : DateTime.MinValue);
					if (c.ColumnName == "TICKER") newRow.Ticker = ((dr["TICKER"] != DBNull.Value) ? (string)dr["TICKER"] : string.Empty);
					if (c.ColumnName == "LOW") newRow.Low = ((dr["LOW"] != DBNull.Value) ? (double)dr["LOW"] : 0);
					if (c.ColumnName == "HIGH") newRow.High = ((dr["HIGH"] != DBNull.Value) ? (double)dr["HIGH"] : 0);
					if (c.ColumnName == "OPEN") newRow.Open = ((dr["OPEN"] != DBNull.Value) ? (double)dr["OPEN"] : 0);
					if (c.ColumnName == "CLOSE") newRow.Close = ((dr["CLOSE"] != DBNull.Value) ? (double)dr["CLOSE"] : 0);
					if (c.ColumnName == "VOLUME") newRow.Volume = ((dr["VOLUME"] != DBNull.Value) ? (double)dr["VOLUME"] : 0);
					if (c.ColumnName == "PERIOD") newRow.Period = ((dr["PERIOD"] != DBNull.Value) ? (int)dr["PERIOD"] : 0);

				}

			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdateHistory(newRow, recId, false, false);
		}

		private void Update_FIRM_HOLDING_TOTAL(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperFirm_Holding_Total();
			try
			{

				foreach (DataColumn c in dr.Table.Columns)
				{

					if (c.ColumnName == "CLIENTID") newRow.ClientID = ((dr["CLIENTID"] != DBNull.Value) ? (int)dr["CLIENTID"] : 0);
					if (c.ColumnName == "TRDACCID") newRow.TrdAccID = ((dr["TRDACCID"] != DBNull.Value) ? (string)dr["TRDACCID"] : string.Empty);
					if (c.ColumnName == "ACCTYPE") newRow.AccType = ((dr["ACCTYPE"] != DBNull.Value) ? (string)dr["ACCTYPE"] : string.Empty);
					if (c.ColumnName == "SECCODE") newRow.SecCode = ((dr["SECCODE"] != DBNull.Value) ? (string)dr["SECCODE"] : string.Empty);
					if (c.ColumnName == "ISSUECODE") newRow.IssueCode = ((dr["ISSUECODE"] != DBNull.Value) ? (string)dr["ISSUECODE"] : string.Empty);
					if (c.ColumnName == "OPENBAL") newRow.OpenBal = ((dr["OPENBAL"] != DBNull.Value) ? (long)dr["OPENBAL"] : 0);
					if (c.ColumnName == "CURRENTPOS") newRow.CurrentPos = ((dr["CURRENTPOS"] != DBNull.Value) ? (long)dr["CURRENTPOS"] : 0);
					if (c.ColumnName == "MIN") newRow.Min = ((dr["MIN"] != DBNull.Value) ? (long)dr["MIN"] : 0);
					if (c.ColumnName == "PLANNEDPOSBUY") newRow.PlannedPosBuy = ((dr["PLANNEDPOSBUY"] != DBNull.Value) ? (long)dr["PLANNEDPOSBUY"] : 0);
					if (c.ColumnName == "PLANNEDPOSSELL") newRow.PlannedPosSell = ((dr["PLANNEDPOSSELL"] != DBNull.Value) ? (long)dr["PLANNEDPOSSELL"] : 0);
					if (c.ColumnName == "TODAYBUY") newRow.TodayBuy = ((dr["TODAYBUY"] != DBNull.Value) ? (long)dr["TODAYBUY"] : 0);
					if (c.ColumnName == "TODAYSELL") newRow.TodaySell = ((dr["TODAYSELL"] != DBNull.Value) ? (long)dr["TODAYSELL"] : 0);
					if (c.ColumnName == "VARMARGIN") newRow.VarMargin = ((dr["VARMARGIN"] != DBNull.Value) ? (double)dr["VARMARGIN"] : 0);
					if (c.ColumnName == "VARMARGINREAL") newRow.VarMarginReal = ((dr["VARMARGINREAL"] != DBNull.Value) ? (double)dr["VARMARGINREAL"] : 0);
					if (c.ColumnName == "VARMARGINOPT") newRow.VarMarginOpt = ((dr["VARMARGINOPT"] != DBNull.Value) ? (double)dr["VARMARGINOPT"] : 0);
					if (c.ColumnName == "FIRMID") newRow.FirmID = ((dr["FIRMID"] != DBNull.Value) ? (string)dr["FIRMID"] : string.Empty);
					if (c.ColumnName == "TICKER") newRow.Ticker = ((dr["TICKER"] != DBNull.Value) ? (string)dr["TICKER"] : string.Empty);

				}

			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdateHoldings(newRow, recId, false, false);
		}

		private void Update_TRDACC(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperTrdAcc();
			try
			{
				foreach (DataColumn c in dr.Table.Columns)
				{

					if (c.ColumnName == "TRDACCID") newRow.TrdAccID = ((dr["TRDACCID"] != DBNull.Value) ? (string)dr["TRDACCID"] : string.Empty);
					if (c.ColumnName == "MAINTRDACCID") newRow.MainTrdAccID = ((dr["MAINTRDACCID"] != DBNull.Value) ? (string)dr["MAINTRDACCID"] : string.Empty);
					if (c.ColumnName == "FIRMID") newRow.FirmID = ((dr["FIRMID"] != DBNull.Value) ? (string)dr["FIRMID"] : string.Empty);
					if (c.ColumnName == "NAME") newRow.Name = ((dr["NAME"] != DBNull.Value) ? (string)dr["NAME"] : string.Empty);
					if (c.ColumnName == "ACCTYPE") newRow.AccType = ((dr["ACCTYPE"] != DBNull.Value) ? (string)dr["ACCTYPE"] : string.Empty);
					if (c.ColumnName == "BANKACCOUNT") newRow.BankAccount = ((dr["BANKACCOUNT"] != DBNull.Value) ? (string)dr["BANKACCOUNT"] : string.Empty);
					if (c.ColumnName == "DEPOACCOUNT") newRow.DepoAccount = ((dr["DEPOACCOUNT"] != DBNull.Value) ? (string)dr["DEPOACCOUNT"] : string.Empty);
					if (c.ColumnName == "BANKCODE") newRow.BankCode = ((dr["BANKCODE"] != DBNull.Value) ? (string)dr["BANKCODE"] : string.Empty);
					if (c.ColumnName == "DEPOCODE") newRow.DepoCode = ((dr["DEPOCODE"] != DBNull.Value) ? (string)dr["DEPOCODE"] : string.Empty);
					if (c.ColumnName == "DESCRIPTION") newRow.Description = ((dr["DESCRIPTION"] != DBNull.Value) ? (string)dr["DESCRIPTION"] : string.Empty);
				}
			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdateTrdacc(newRow, recId, false, false);
		}

		private void Update_TRADES(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperTrades();
			try
			{

				foreach (DataColumn c in dr.Table.Columns)
				{
					if (c.ColumnName == "TRADENO") newRow.TradeNo = ((dr["TRADENO"] != DBNull.Value) ? (long)dr["TRADENO"] : 0);
					if (c.ColumnName == "TRADETIME") newRow.TradeTime = ((dr["TRADETIME"] != DBNull.Value) ? (DateTime)dr["TRADETIME"] : DateTime.MinValue);
					if (c.ColumnName == "ISSUECODE") newRow.IssueCode = ((dr["ISSUECODE"] != DBNull.Value) ? (string)dr["ISSUECODE"] : string.Empty);
					if (c.ColumnName == "REPORATE") newRow.RepoRate = ((dr["REPORATE"] != DBNull.Value) ? (double)dr["REPORATE"] : 0);
					if (c.ColumnName == "REPOTERM") newRow.RepoTerm = ((dr["REPOTERM"] != DBNull.Value) ? (int)dr["REPOTERM"] : 0);
					if (c.ColumnName == "STARTDISCOUNT") newRow.StartDiscount = ((dr["STARTDISCOUNT"] != DBNull.Value) ? (double)dr["STARTDISCOUNT"] : 0);
					if (c.ColumnName == "COMMISSION") newRow.Commission = ((dr["COMMISSION"] != DBNull.Value) ? (double)dr["COMMISSION"] : 0);
					if (c.ColumnName == "TRADETYPE") newRow.TradeType = ((dr["TRADETYPE"] != DBNull.Value) ? (string)dr["TRADETYPE"] : string.Empty);
					if (c.ColumnName == "SETTLECODE") newRow.SettleCode = ((dr["SETTLECODE"] != DBNull.Value) ? (string)dr["SETTLECODE"] : string.Empty);
					if (c.ColumnName == "ORDERNO") newRow.OrderNo = ((dr["ORDERNO"] != DBNull.Value) ? (long)dr["ORDERNO"] : 0);
					if (c.ColumnName == "BUYSELL") newRow.BuySell = ((dr["BUYSELL"] != DBNull.Value) ? (string)dr["BUYSELL"] : string.Empty);
					if (c.ColumnName == "BROKERREF") newRow.BrokerRef = ((dr["BROKERREF"] != DBNull.Value) ? (string)dr["BROKERREF"] : string.Empty);
					if (c.ColumnName == "BROKERID") newRow.BrokerID = ((dr["BROKERID"] != DBNull.Value) ? (string)dr["BROKERID"] : string.Empty);
					if (c.ColumnName == "USERID") newRow.UserID = ((dr["USERID"] != DBNull.Value) ? (string)dr["USERID"] : string.Empty);
					if (c.ColumnName == "FIRMID") newRow.FirmID = ((dr["FIRMID"] != DBNull.Value) ? (string)dr["FIRMID"] : string.Empty);
					if (c.ColumnName == "ACCOUNT") newRow.Account = ((dr["ACCOUNT"] != DBNull.Value) ? (string)dr["ACCOUNT"] : string.Empty);
					if (c.ColumnName == "SECID") newRow.SecID = ((dr["SECID"] != DBNull.Value) ? (int)dr["SECID"] : 0);
					if (c.ColumnName == "SECBOARD") newRow.SecBoard = ((dr["SECBOARD"] != DBNull.Value) ? (string)dr["SECBOARD"] : string.Empty);
					if (c.ColumnName == "SECCODE") newRow.SecCode = ((dr["SECCODE"] != DBNull.Value) ? (string)dr["SECCODE"] : string.Empty);
					if (c.ColumnName == "PRICE") newRow.Price = ((dr["PRICE"] != DBNull.Value) ? (double)dr["PRICE"] : 0);
					if (c.ColumnName == "QUANTITY") newRow.Quantity = ((dr["QUANTITY"] != DBNull.Value) ? (int)dr["QUANTITY"] : 0);
					if (c.ColumnName == "VALUE") newRow.Value = ((dr["VALUE"] != DBNull.Value) ? (double)dr["VALUE"] : 0);
					if (c.ColumnName == "ACCRUEDINT") newRow.AccruedInt = ((dr["ACCRUEDINT"] != DBNull.Value) ? (double)dr["ACCRUEDINT"] : 0);
					if (c.ColumnName == "YIELD") newRow.Yield = ((dr["YIELD"] != DBNull.Value) ? (double)dr["YIELD"] : 0);
					if (c.ColumnName == "PERIOD") newRow.Period = ((dr["PERIOD"] != DBNull.Value) ? (string)dr["PERIOD"] : string.Empty);
					if (c.ColumnName == "EXTREF") newRow.ExtRef = ((dr["EXTREF"] != DBNull.Value) ? (string)dr["EXTREF"] : string.Empty);

				}
			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdateTrades(newRow, recId, false, false);
		}

		private void Update_STOPORDERS(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperStopOrders();
			try
			{

				foreach (DataColumn c in dr.Table.Columns)
				{
					if (c.ColumnName == "STOPTYPE") newRow.StopType = ((dr["STOPTYPE"] != DBNull.Value) ? (string)dr["STOPTYPE"] : string.Empty);
					if (c.ColumnName == "ORDERENDTIME") newRow.OrderEndTime = ((dr["ORDERENDTIME"] != DBNull.Value) ? (DateTime)dr["ORDERENDTIME"] : DateTime.MinValue);
					if (c.ColumnName == "ENDTIME") newRow.EndTime = ((dr["ENDTIME"] != DBNull.Value) ? (DateTime)dr["ENDTIME"] : DateTime.MinValue);
					if (c.ColumnName == "ALERTPRICE") newRow.AlertPrice = ((dr["ALERTPRICE"] != DBNull.Value) ? (double)dr["ALERTPRICE"] : 0);
					if (c.ColumnName == "ORDERNO") newRow.OrderNo = ((dr["ORDERNO"] != DBNull.Value) ? (long)dr["ORDERNO"] : 0);
					if (c.ColumnName == "ORDERTIME") newRow.OrderTime = ((dr["ORDERTIME"] != DBNull.Value) ? (DateTime)dr["ORDERTIME"] : DateTime.MinValue);
					if (c.ColumnName == "WITHDRAWTIME") newRow.WithdrawTime = ((dr["WITHDRAWTIME"] != DBNull.Value) ? (DateTime)dr["WITHDRAWTIME"] : DateTime.MinValue);
					if (c.ColumnName == "STATUS") newRow.Status = ((dr["STATUS"] != DBNull.Value) ? (string)dr["STATUS"] : string.Empty);
					if (c.ColumnName == "MKTLIMIT") newRow.MktLimit = ((dr["MKTLIMIT"] != DBNull.Value) ? (string)dr["MKTLIMIT"] : string.Empty);
					if (c.ColumnName == "BUYSELL") newRow.BuySell = ((dr["BUYSELL"] != DBNull.Value) ? (string)dr["BUYSELL"] : string.Empty);
					if (c.ColumnName == "SPLITFLAG") newRow.SplitFlag = ((dr["SPLITFLAG"] != DBNull.Value) ? (string)dr["SPLITFLAG"] : string.Empty);
					if (c.ColumnName == "IMMCANCEL") newRow.ImmCancel = ((dr["IMMCANCEL"] != DBNull.Value) ? (string)dr["IMMCANCEL"] : string.Empty);
					if (c.ColumnName == "BROKERREF") newRow.BrokerRef = ((dr["BROKERREF"] != DBNull.Value) ? (string)dr["BROKERREF"] : string.Empty);
					if (c.ColumnName == "BROKERID") newRow.BrokerID = ((dr["BROKERID"] != DBNull.Value) ? (string)dr["BROKERID"] : string.Empty);
					if (c.ColumnName == "ACCOUNT") newRow.Account = ((dr["ACCOUNT"] != DBNull.Value) ? (string)dr["ACCOUNT"] : string.Empty);
					if (c.ColumnName == "SECBOARD") newRow.SecBoard = ((dr["SECBOARD"] != DBNull.Value) ? (string)dr["SECBOARD"] : string.Empty);
					if (c.ColumnName == "SECCODE") newRow.SecCode = ((dr["SECCODE"] != DBNull.Value) ? (string)dr["SECCODE"] : string.Empty);
					if (c.ColumnName == "PRICE") newRow.Price = ((dr["PRICE"] != DBNull.Value) ? (double)dr["PRICE"] : 0);
					if (c.ColumnName == "QUANTITY") newRow.Quantity = ((dr["QUANTITY"] != DBNull.Value) ? (int)dr["QUANTITY"] : 0);
					if (c.ColumnName == "ACCRUEDINT") newRow.AccruedInt = ((dr["ACCRUEDINT"] != DBNull.Value) ? (double)dr["ACCRUEDINT"] : 0);
					if (c.ColumnName == "YIELD") newRow.Yield = ((dr["YIELD"] != DBNull.Value) ? (double)dr["YIELD"] : 0);
					if (c.ColumnName == "EXTREF") newRow.ExtRef = ((dr["EXTREF"] != DBNull.Value) ? (string)dr["EXTREF"] : string.Empty);
				}
			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdateStoporders(newRow, recId, false, false);
		}

		private void Update_POSITIONS(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperPositions();
			/*
			 * ClientID, TrdAccID, OpenBal, CurrentPos, PlannedPos, OrderBuy, OrderSell, Netto, Portfolio, Value, 
			 * Commission, Commission2, PlannedCommission, PlannedCommission2, Profit, Free, FreeForShorting, FreeForMargin, FreeForNonMargin, MarginLevel, 
			 * MarginLevelPlanned, FirmID*, CurrCode, Tag, BankAccID, Description, MarginTrading, UseMarginLevel, AccCode, LiquidityRate, 
			 * GuaranteeFactor, PrevLimit, CBPLimit, CBPLUsed, CBPPlanned, Reserved, Surplus, VarMargin, VarMarginOpt, VarMarginReal
			*/
			try
			{
				foreach (DataColumn c in dr.Table.Columns)
				{
					if (c.ColumnName == "CLIENTID") newRow.ClientID = ((dr["CLIENTID"] != DBNull.Value) ? (int)dr["CLIENTID"] : 0);
					if (c.ColumnName == "TRDACCID") newRow.TrdAccID = ((dr["TRDACCID"] != DBNull.Value) ? (string)dr["TRDACCID"] : string.Empty);
					if (c.ColumnName == "OPENBAL") newRow.OpenBal = ((dr["OPENBAL"] != DBNull.Value) ? (double)dr["OPENBAL"] : 0);
					if (c.ColumnName == "CURRENTPOS") newRow.CurrentPos = ((dr["CURRENTPOS"] != DBNull.Value) ? (double)dr["CURRENTPOS"] : 0);
					if (c.ColumnName == "PLANNEDPOS") newRow.PlannedPos = ((dr["PLANNEDPOS"] != DBNull.Value) ? (double)dr["PLANNEDPOS"] : 0);
					if (c.ColumnName == "ORDERBUY") newRow.OrderBuy = ((dr["ORDERBUY"] != DBNull.Value) ? (double)dr["ORDERBUY"] : 0);
					if (c.ColumnName == "ORDERSELL") newRow.OrderSell = ((dr["ORDERSELL"] != DBNull.Value) ? (double)dr["ORDERSELL"] : 0);
					if (c.ColumnName == "NETTO") newRow.Netto = ((dr["NETTO"] != DBNull.Value) ? (double)dr["NETTO"] : 0);
					if (c.ColumnName == "PORTFOLIO") newRow.Portfolio = ((dr["PORTFOLIO"] != DBNull.Value) ? (double)dr["PORTFOLIO"] : 0);
					if (c.ColumnName == "VALUE") newRow.Value = ((dr["VALUE"] != DBNull.Value) ? (double)dr["VALUE"] : 0);
					if (c.ColumnName == "COMMISSION") newRow.Commission = ((dr["COMMISSION"] != DBNull.Value) ? (double)dr["COMMISSION"] : 0);
					if (c.ColumnName == "COMMISSION2") newRow.Commission2 = ((dr["COMMISSION2"] != DBNull.Value) ? (double)dr["COMMISSION2"] : 0);
					if (c.ColumnName == "PLANNEDCOMMISSION") newRow.PlannedCommission = ((dr["PLANNEDCOMMISSION"] != DBNull.Value) ? (double)dr["PLANNEDCOMMISSION"] : 0);
					if (c.ColumnName == "PLANNEDCOMMISSION2") newRow.PlannedCommission2 = ((dr["PLANNEDCOMMISSION2"] != DBNull.Value) ? (double)dr["PLANNEDCOMMISSION2"] : 0);
					if (c.ColumnName == "PROFIT") newRow.Profit = ((dr["PROFIT"] != DBNull.Value) ? (double)dr["PROFIT"] : 0);
					if (c.ColumnName == "FREE") newRow.Free = ((dr["FREE"] != DBNull.Value) ? (double)dr["FREE"] : 0);
					if (c.ColumnName == "FREEFORSHORTING") newRow.FreeForShorting = ((dr["FREEFORSHORTING"] != DBNull.Value) ? (double)dr["FREEFORSHORTING"] : 0);
					if (c.ColumnName == "FREEFORMARGIN") newRow.FreeForMargin = ((dr["FREEFORMARGIN"] != DBNull.Value) ? (double)dr["FREEFORMARGIN"] : 0);
					if (c.ColumnName == "FREEFORNONMARGIN") newRow.FreeForNonMargin = ((dr["FREEFORNONMARGIN"] != DBNull.Value) ? (double)dr["FREEFORNONMARGIN"] : 0);
					if (c.ColumnName == "MARGINLEVEL") newRow.MarginLevel = ((dr["MARGINLEVEL"] != DBNull.Value) ? (double)dr["MARGINLEVEL"] : 0);
					if (c.ColumnName == "MARGINLEVELPLANNED") newRow.MarginLevelPlanned = ((dr["MARGINLEVELPLANNED"] != DBNull.Value) ? (double)dr["MARGINLEVELPLANNED"] : 0);
					if (c.ColumnName == "FIRMID") newRow.FirmID = ((dr["FIRMID"] != DBNull.Value) ? (string)dr["FIRMID"] : string.Empty);
					if (c.ColumnName == "CURRCODE") newRow.CurrCode = ((dr["CURRCODE"] != DBNull.Value) ? (string)dr["CURRCODE"] : string.Empty);
					if (c.ColumnName == "TAG") newRow.Tag = ((dr["TAG"] != DBNull.Value) ? (string)dr["TAG"] : string.Empty);
					if (c.ColumnName == "BANKACCID") newRow.BankAccID = ((dr["BANKACCID"] != DBNull.Value) ? (string)dr["BANKACCID"] : string.Empty);
					if (c.ColumnName == "DESCRIPTION") newRow.Description = ((dr["DESCRIPTION"] != DBNull.Value) ? (string)dr["DESCRIPTION"] : string.Empty);
					if (c.ColumnName == "MARGINTRADING") newRow.MarginTrading = ((dr["MARGINTRADING"] != DBNull.Value) ? (bool)dr["MARGINTRADING"] : false);
					if (c.ColumnName == "USEMARGINLEVEL") newRow.UseMarginLevel = ((dr["USEMARGINLEVEL"] != DBNull.Value) ? (bool)dr["USEMARGINLEVEL"] : false);
					if (c.ColumnName == "ACCCODE") newRow.AccCode = ((dr["ACCCODE"] != DBNull.Value) ? (string)dr["ACCCODE"] : string.Empty);
					if (c.ColumnName == "LIQUIDITYRATE") newRow.LiquidityRate = ((dr["LIQUIDITYRATE"] != DBNull.Value) ? (double)dr["LIQUIDITYRATE"] : 0);
					if (c.ColumnName == "GUARANTEEFACTOR") newRow.GuaranteeFactor = ((dr["GUARANTEEFACTOR"] != DBNull.Value) ? (double)dr["GUARANTEEFACTOR"] : 0);
					if (c.ColumnName == "PREVLIMIT") newRow.PrevLimit = ((dr["PREVLIMIT"] != DBNull.Value) ? (double)dr["PREVLIMIT"] : 0);
					if (c.ColumnName == "CBPLIMIT") newRow.CBPLimit = ((dr["CBPLIMIT"] != DBNull.Value) ? (double)dr["CBPLIMIT"] : 0);
					if (c.ColumnName == "CBPLUSED") newRow.CBPLUsed = ((dr["CBPLUSED"] != DBNull.Value) ? (double)dr["CBPLUSED"] : 0);
					if (c.ColumnName == "CBPPLANNED") newRow.CBPPlanned = ((dr["CBPPLANNED"] != DBNull.Value) ? (double)dr["CBPPLANNED"] : 0);
					if (c.ColumnName == "RESERVED") newRow.Reserved = ((dr["RESERVED"] != DBNull.Value) ? (double)dr["RESERVED"] : 0);
					if (c.ColumnName == "SURPLUS") newRow.Surplus = ((dr["SURPLUS"] != DBNull.Value) ? (double)dr["SURPLUS"] : 0);
					if (c.ColumnName == "VARMARGIN") newRow.VarMargin = ((dr["VARMARGIN"] != DBNull.Value) ? (double)dr["VARMARGIN"] : 0);
					if (c.ColumnName == "VARMARGINOPT") newRow.VarMarginOpt = ((dr["VARMARGINOPT"] != DBNull.Value) ? (double)dr["VARMARGINOPT"] : 0);
					if (c.ColumnName == "VARMARGINREAL") newRow.VarMarginReal = ((dr["VARMARGINREAL"] != DBNull.Value) ? (double)dr["VARMARGINREAL"] : 0);
				}
			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdatePositions(newRow, recId, false, false);
		}

		private void Update_ORDERBOOK(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperOrderbook();
			// SecBoard, SecCode, BuySell, Price, Quantity, 
			try
			{

				foreach (DataColumn c in dr.Table.Columns)
				{
					if (c.ColumnName == "BUYSELL") newRow.BuySell = ((dr["BUYSELL"] != DBNull.Value) ? (string)dr["BUYSELL"] : string.Empty);
					if (c.ColumnName == "SECBOARD") newRow.SecBoard = ((dr["SECBOARD"] != DBNull.Value) ? (string)dr["SECBOARD"] : string.Empty);
					if (c.ColumnName == "SECCODE") newRow.SecCode = ((dr["SECCODE"] != DBNull.Value) ? (string)dr["SECCODE"] : string.Empty);
					if (c.ColumnName == "PRICE") newRow.Price = ((dr["PRICE"] != DBNull.Value) ? (double)dr["PRICE"] : 0);
					if (c.ColumnName == "QUANTITY") newRow.Quantity = ((dr["QUANTITY"] != DBNull.Value) ? (int)dr["QUANTITY"] : 0);

					if (newRow.SecBoard == string.Empty || newRow.SecBoard == null)
					{
						char[] charr = new char[4];
						tableName.CopyTo(10, charr, 0, 4);
						StringBuilder sb = new StringBuilder(4);
						foreach (var item in charr)
						{
							sb.Append(item);
						}
						newRow.SecBoard = sb.ToString();
					}

					if (newRow.SecCode == string.Empty || newRow.SecCode == null)
					{
						char[] charr = new char[9];
						tableName.CopyTo(14, charr, 0, tableName.Length - 14);
						StringBuilder sb = new StringBuilder(9);
						foreach (var item in charr)
						{
							sb.Append(item);
						}
						newRow.SecCode = sb.ToString();
					}

				}
			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdateOrderBook(newRow, recId, false, false);
		}

		private void Update_ORDERS(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperOrders();
			// OrderNo, OrderTime, WithdrawTime, Status, MktLimit, 
			// BuySell, SplitFlag, ImmCancel, EntryType, MarketMaker, 
			// BrokerRef, BrokerID, UserID, FirmID, Account, 
			// SecID, SecBoard, SecCode, Price, Price2, 
			// Quantity, Balance, Value, AccruedInt, EnterType, 
			// Yield, Period, ExtRef, MarketMaker
			try
			{
				foreach (DataColumn c in dr.Table.Columns)
				{
					if (c.ColumnName == "ORDERNO") newRow.OrderNo = ((dr["ORDERNO"] != DBNull.Value) ? (long)dr["ORDERNO"] : 0);
					if (c.ColumnName == "ORDERTIME") newRow.OrderTime = ((dr["ORDERTIME"] != DBNull.Value) ? (DateTime)dr["ORDERTIME"] : DateTime.MinValue);
					if (c.ColumnName == "WITHDRAWTIME") newRow.WithdrawTime = ((dr["WITHDRAWTIME"] != DBNull.Value) ? (DateTime)dr["WITHDRAWTIME"] : DateTime.MinValue);
					if (c.ColumnName == "STATUS") newRow.Status = ((dr["STATUS"] != DBNull.Value) ? (string)dr["STATUS"] : string.Empty);
					if (c.ColumnName == "MKTLIMIT") newRow.MktLimit = ((dr["MKTLIMIT"] != DBNull.Value) ? (string)dr["MKTLIMIT"] : string.Empty);
					if (c.ColumnName == "BUYSELL") newRow.BuySell = ((dr["BUYSELL"] != DBNull.Value) ? (string)dr["BUYSELL"] : string.Empty);
					if (c.ColumnName == "SPLITFLAG") newRow.SplitFlag = ((dr["SPLITFLAG"] != DBNull.Value) ? (string)dr["SPLITFLAG"] : string.Empty);
					if (c.ColumnName == "IMMCANCEL") newRow.ImmCancel = ((dr["IMMCANCEL"] != DBNull.Value) ? (string)dr["IMMCANCEL"] : string.Empty);
					if (c.ColumnName == "ENTRYTYPE") newRow.EntryType = ((dr["ENTRYTYPE"] != DBNull.Value) ? (string)dr["ENTRYTYPE"] : string.Empty);
					if (c.ColumnName == "MARKETMAKER") newRow.MarketMaker = ((dr["MARKETMAKER"] != DBNull.Value) ? (string)dr["MARKETMAKER"] : string.Empty);
					if (c.ColumnName == "BROKERREF") newRow.BrokerRef = ((dr["BROKERREF"] != DBNull.Value) ? (string)dr["BROKERREF"] : string.Empty);
					if (c.ColumnName == "BROKERID") newRow.BrokerID = ((dr["BROKERID"] != DBNull.Value) ? (string)dr["BROKERID"] : string.Empty);
					if (c.ColumnName == "USERID") newRow.UserID = ((dr["USERID"] != DBNull.Value) ? (string)dr["USERID"] : string.Empty);
					if (c.ColumnName == "FIRMID") newRow.FirmID = ((dr["FIRMID"] != DBNull.Value) ? (string)dr["FIRMID"] : string.Empty);
					if (c.ColumnName == "ACCOUNT") newRow.Account = ((dr["ACCOUNT"] != DBNull.Value) ? (string)dr["ACCOUNT"] : string.Empty);
					if (c.ColumnName == "SECID") newRow.SecID = ((dr["SECID"] != DBNull.Value) ? (int)dr["SECID"] : 0);
					if (c.ColumnName == "SECBOARD") newRow.SecBoard = ((dr["SECBOARD"] != DBNull.Value) ? (string)dr["SECBOARD"] : string.Empty);
					if (c.ColumnName == "SECCODE") newRow.SecCode = ((dr["SECCODE"] != DBNull.Value) ? (string)dr["SECCODE"] : string.Empty);
					if (c.ColumnName == "PRICE") newRow.Price = ((dr["PRICE"] != DBNull.Value) ? (double)dr["PRICE"] : 0);
					if (c.ColumnName == "PRICE2") newRow.Price2 = ((dr["PRICE2"] != DBNull.Value) ? (double)dr["PRICE2"] : 0);
					if (c.ColumnName == "QUANTITY") newRow.Quantity = ((dr["QUANTITY"] != DBNull.Value) ? (int)dr["QUANTITY"] : 0);
					if (c.ColumnName == "BALANCE") newRow.Balance = ((dr["BALANCE"] != DBNull.Value) ? (int)dr["BALANCE"] : 0);
					if (c.ColumnName == "VALUE") newRow.Value = ((dr["VALUE"] != DBNull.Value) ? (double)dr["VALUE"] : 0);
					if (c.ColumnName == "ACCRUEDINT") newRow.AccruedInt = ((dr["ACCRUEDINT"] != DBNull.Value) ? (double)dr["ACCRUEDINT"] : 0);
					if (c.ColumnName == "ENTERTYPE") newRow.EnterType = ((dr["ENTERTYPE"] != DBNull.Value) ? (string)dr["ENTERTYPE"] : string.Empty);
					if (c.ColumnName == "YIELD") newRow.Yield = ((dr["YIELD"] != DBNull.Value) ? (double)dr["YIELD"] : 0);
					if (c.ColumnName == "PERIOD") newRow.Period = ((dr["PERIOD"] != DBNull.Value) ? (string)dr["PERIOD"] : string.Empty);
					if (c.ColumnName == "EXTREF") newRow.ExtRef = ((dr["EXTREF"] != DBNull.Value) ? (string)dr["EXTREF"] : string.Empty);
					if (c.ColumnName == "MARKETMAKER") newRow.MarketMaker = ((dr["MARKETMAKER"] != DBNull.Value) ? (string)dr["MARKETMAKER"] : string.Empty);

				}

			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdateOrders(newRow, recId, false, false);
		}


		private void Update_NEWS(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperNews();
			//NewsNo, Time, ContentType, Source, Subject, Body
			try
			{

				foreach (DataColumn c in dr.Table.Columns)
				{

					if (c.ColumnName == "NEWSNO") newRow.NewsNo = ((dr["NEWSNO"] != DBNull.Value) ? (int)dr["NEWSNO"] : 0);
					if (c.ColumnName == "TIME") newRow.Time = ((dr["TIME"] != DBNull.Value) ? (DateTime)dr["TIME"] : DateTime.MinValue);
					if (c.ColumnName == "CONTENTTYPE") newRow.ContentType = ((dr["CONTENTTYPE"] != DBNull.Value) ? (string)dr["CONTENTTYPE"] : string.Empty);
					if (c.ColumnName == "SOURCE") newRow.ContentType = ((dr["SOURCE"] != DBNull.Value) ? (string)dr["SOURCE"] : string.Empty);
					if (c.ColumnName == "SUBJECT") newRow.ContentType = ((dr["SUBJECT"] != DBNull.Value) ? (string)dr["SUBJECT"] : string.Empty);
					if (c.ColumnName == "BODY") newRow.ContentType = ((dr["BODY"] != DBNull.Value) ? (string)dr["BODY"] : string.Empty);

				}
			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdateNews(newRow, recId, false, false);
		}

		private void Update_INDEXES(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperIndexes();
			//"SHORTNAME, NAME, DECIMALS, CURRENTVALUE, HIGH, LOW, INDEXBOARD, INDEXCODE, PREVCLOSE, TIME, USDRATE"
			try
			{
				foreach (DataColumn c in dr.Table.Columns)
				{

					if (c.ColumnName == "SHORTNAME") newRow.ShortName = ((dr["SHORTNAME"] != DBNull.Value) ? (string)dr["SHORTNAME"] : string.Empty);
					if (c.ColumnName == "NAME") newRow.Name = ((dr["NAME"] != DBNull.Value) ? (string)dr["NAME"] : string.Empty);
					if (c.ColumnName == "DECIMALS") newRow.Decimals = ((dr["DECIMALS"] != DBNull.Value) ? (byte)dr["DECIMALS"] : 0);
					if (c.ColumnName == "CURRENTVALUE") newRow.CurrentValue = dr["CURRENTVALUE"] != DBNull.Value ? (double)dr["CURRENTVALUE"] : 0;
					if (c.ColumnName == "HIGH") newRow.High = dr["HIGH"] != DBNull.Value ? (double)dr["HIGH"] : 0;
					if (c.ColumnName == "LOW") newRow.Low = dr["LOW"] != DBNull.Value ? (double)dr["LOW"] : 0;
					if (c.ColumnName == "INDEXBOARD") newRow.IndexBoard = ((dr["INDEXBOARD"] != DBNull.Value) ? (string)dr["INDEXBOARD"] : string.Empty);
					if (c.ColumnName == "INDEXCODE") newRow.IndexCode = ((dr["INDEXCODE"] != DBNull.Value) ? (string)dr["INDEXCODE"] : string.Empty);
					if (c.ColumnName == "PREVCLOSE") newRow.PrevClose = dr["PREVCLOSE"] != DBNull.Value ? (double)dr["PREVCLOSE"] : 0;
					if (c.ColumnName == "TIME") newRow.Time = ((dr["TIME"] != DBNull.Value) ? (DateTime)dr["TIME"] : DateTime.MinValue);
					if (c.ColumnName == "USDRATE") newRow.UsdRate = dr["USDRATE"] != DBNull.Value ? (double)dr["USDRATE"] : 0;

				}
			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdateIndexes(newRow, recId, false, false);
		}

		private void Update_SECURITIES(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperSecurities();
			//"SHORTNAME, SECBOARD, SECCODE, SECNAME, DECIMALS, BID, OFFER, LOW, HIGH, PREVPRICE, OPEN, LAST, NUMTRADES, TIME, STEPPRICE, TRADINGSTATUS, TICKER";
			try
			{
				foreach (DataColumn c in dr.Table.Columns)
				{

					if (c.ColumnName == "SHORTNAME") newRow.ShortName = ((dr["SHORTNAME"] != DBNull.Value) ? (string)dr["SHORTNAME"] : string.Empty);
					if (c.ColumnName == "SECBOARD") newRow.SecBoard = (string)((dr["SECBOARD"] != DBNull.Value) ? (string)dr["SECBOARD"] : string.Empty);
					if (c.ColumnName == "SECCODE") newRow.SecCode = (string)((dr["SECCODE"] != DBNull.Value) ? (string)dr["SECCODE"] : string.Empty);
					if (c.ColumnName == "SECNAME") newRow.SecName = (string)((dr["SECNAME"] != DBNull.Value) ? (string)dr["SECNAME"] : string.Empty);
					if (c.ColumnName == "DECIMALS") newRow.Decimals = ((dr["DECIMALS"] != DBNull.Value) ? (byte)dr["DECIMALS"] : 0);
					if (c.ColumnName == "BID") newRow.Bid = ((dr["BID"] != DBNull.Value) ? (double)dr["BID"] : 0);
					if (c.ColumnName == "OFFER") newRow.Offer = ((dr["OFFER"] != DBNull.Value) ? (double)dr["OFFER"] : 0);
					if (c.ColumnName == "LOW") newRow.Low = ((dr["LOW"] != DBNull.Value) ? (double)dr["LOW"] : 0);
					if (c.ColumnName == "HIGH") newRow.High = ((dr["HIGH"] != DBNull.Value) ? (double)dr["HIGH"] : 0);
					if (c.ColumnName == "PREVPRICE") newRow.PrevPrice = ((dr["PREVPRICE"] != DBNull.Value) ? (double)dr["PREVPRICE"] : 0);
					if (c.ColumnName == "OPEN") newRow.Open = ((dr["OPEN"] != DBNull.Value) ? (double)dr["OPEN"] : 0);
					if (c.ColumnName == "LAST") newRow.Last = ((dr["LAST"] != DBNull.Value) ? (double)dr["LAST"] : 0);
					if (c.ColumnName == "NUMTRADES") newRow.NumTrades = ((dr["NUMTRADES"] != DBNull.Value) ? (int)dr["NUMTRADES"] : 0);
					if (c.ColumnName == "TIME") newRow.Time = ((dr["TIME"] != DBNull.Value) ? (DateTime)dr["TIME"] : DateTime.MinValue);
					if (c.ColumnName == "STEPPRICE") newRow.StepPrice = ((dr["STEPPRICE"] != DBNull.Value) ? (double)dr["STEPPRICE"] : 0);
					if (c.ColumnName == "TRADINGSTATUS") newRow.TradingStatus = ((dr["TRADINGSTATUS"] != DBNull.Value) ? (string)dr["TRADINGSTATUS"] : string.Empty);
					if (c.ColumnName == "TICKER") newRow.Ticker = ((dr["TICKER"] != DBNull.Value) ? (string)dr["TICKER"] : string.Empty);

				}
			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdateSecurities(newRow, recId, false, false);
		}

		private void ALL_TRADES_UpdateRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Update_ALL_TRADES, e);
		}

		private void TESYSTIME_UpdateRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Update_TESYSTIME, e);
		}

		private void BOARDS_UpdateRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Update_BOARDS, e);
		}
		private void HISTORY_DAILY_UpdateRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Update_HISTORY_DAILY, e);
		}

		private void HISTORY_UpdateRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Update_HISTORY, e);
		}

		private void FIRM_HOLDING_TOTAL_UpdateRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Update_FIRM_HOLDING_TOTAL, e);
		}

		private void TRDACC_UpdateRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Update_TRDACC, e);
		}


		private void TRADES_UpdateRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Update_TRADES, e);
		}

		private void STOPORDERS_UpdateRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Update_STOPORDERS, e);
		}

		private void POSITIONS_UpdateRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Update_POSITIONS, e);
		}

		private void ORDERBOOK_UpdateRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Update_ORDERBOOK, e);
		}

		private void ORDERS_UpdateRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Update_ORDERS, e);
		}
		private void NEWS_UpdateRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Update_NEWS, e);
		}

		private void INDEXES_UpdateRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Update_INDEXES, e);
		}

		private void SECURITIES_UpdateRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Update_SECURITIES, e);
		}


		#endregion Обновление данных

		#region Добавление данных

		private void Add_ALL_TRADES(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperAll_Trades();
			try
			{

				foreach (DataColumn c in dr.Table.Columns)
				{
					if (c.ColumnName == "TRADENO") newRow.TradeNo = ((dr["TRADENO"] != DBNull.Value) ? (long)dr["TRADENO"] : 0);
					if (c.ColumnName == "TRADETIME") newRow.TradeTime = ((dr["TRADETIME"] != DBNull.Value) ? (DateTime)dr["TRADETIME"] : DateTime.MinValue);
					if (c.ColumnName == "REPORATE") newRow.RepoRate = ((dr["REPORATE"] != DBNull.Value) ? (double)dr["REPORATE"] : 0);
					if (c.ColumnName == "REPOTERM") newRow.RepoTerm = ((dr["REPOTERM"] != DBNull.Value) ? (int)dr["REPOTERM"] : 0);
					if (c.ColumnName == "STARTDISCOUNT") newRow.StartDiscount = ((dr["STARTDISCOUNT"] != DBNull.Value) ? (double)dr["STARTDISCOUNT"] : 0);
					if (c.ColumnName == "TRADETYPE") newRow.TradeType = ((dr["TRADETYPE"] != DBNull.Value) ? (string)dr["TRADETYPE"] : string.Empty);
					if (c.ColumnName == "SETTLECODE") newRow.SettleCode = ((dr["SETTLECODE"] != DBNull.Value) ? (string)dr["SETTLECODE"] : string.Empty);
					if (c.ColumnName == "SECID") newRow.SecID = ((dr["SECID"] != DBNull.Value) ? (int)dr["SECID"] : 0);
					if (c.ColumnName == "SECBOARD") newRow.SecBoard = ((dr["SECBOARD"] != DBNull.Value) ? (string)dr["SECBOARD"] : string.Empty);
					if (c.ColumnName == "SECCODE") newRow.SecCode = ((dr["SECCODE"] != DBNull.Value) ? (string)dr["SECCODE"] : string.Empty);
					if (c.ColumnName == "PRICE") newRow.Price = ((dr["PRICE"] != DBNull.Value) ? (double)dr["PRICE"] : 0);
					if (c.ColumnName == "QUANTITY") newRow.Quantity = ((dr["QUANTITY"] != DBNull.Value) ? (int)dr["QUANTITY"] : 0);
					if (c.ColumnName == "VALUE") newRow.Value = ((dr["VALUE"] != DBNull.Value) ? (double)dr["VALUE"] : 0);
					if (c.ColumnName == "ACCRUEDINT") newRow.AccruedInt = ((dr["ACCRUEDINT"] != DBNull.Value) ? (double)dr["ACCRUEDINT"] : 0);
					if (c.ColumnName == "YIELD") newRow.Yield = ((dr["YIELD"] != DBNull.Value) ? (double)dr["YIELD"] : 0);
					if (c.ColumnName == "PERIOD") newRow.Period = ((dr["PERIOD"] != DBNull.Value) ? (string)dr["PERIOD"] : string.Empty);
					if (c.ColumnName == "ROWSTATE") newRow.RowState = ((dr["ROWSTATE"] != DBNull.Value) ? (byte)dr["ROWSTATE"] : Convert.ToByte(0));
				}

			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdateAll_Trades(newRow, recId, false, false);
		}

		private void Add_TESYSTIME(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperTesystime();
			try
			{

				foreach (DataColumn c in dr.Table.Columns)
				{
					if (c.ColumnName == "TIME") newRow.Time = ((dr["TIME"] != DBNull.Value) ? (DateTime)dr["TIME"] : DateTime.MinValue);
				}
			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdateSystime(newRow, recId, false, false);
		}

		private void Add_BOARDS(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperBoards();
			try
			{

				foreach (DataColumn c in dr.Table.Columns)
				{
					if (c.ColumnName == "BOARDID") newRow.BoardID = ((dr["BOARDID"] != DBNull.Value) ? (string)dr["BOARDID"] : string.Empty);
					if (c.ColumnName == "BOARDNAME") newRow.BoardName = ((dr["BOARDNAME"] != DBNull.Value) ? (string)dr["BOARDNAME"] : string.Empty);
					if (c.ColumnName == "STATUS") newRow.Status = ((dr["STATUS"] != DBNull.Value) ? (string)dr["STATUS"] : string.Empty);
					if (c.ColumnName == "MARKETID") newRow.MarketID = ((dr["MARKETID"] != DBNull.Value) ? (string)dr["MARKETID"] : string.Empty);
				}
			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdateBoards(newRow, recId, false, false);
		}

		private void Add_HISTORY_DAILY(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperHistory_Daily();
			try
			{

				foreach (DataColumn c in dr.Table.Columns)
				{
					if (c.ColumnName == "RECID") newRow.RecID = ((dr["RECID"] != DBNull.Value) ? (long)dr["RECID"] : 0);
					if (c.ColumnName == "TIME") newRow.Time = ((dr["TIME"] != DBNull.Value) ? (DateTime)dr["TIME"] : DateTime.MinValue);
					if (c.ColumnName == "TICKER") newRow.Ticker = ((dr["TICKER"] != DBNull.Value) ? (string)dr["TICKER"] : string.Empty);
					if (c.ColumnName == "LOW") newRow.Low = ((dr["LOW"] != DBNull.Value) ? (double)dr["LOW"] : 0);
					if (c.ColumnName == "HIGH") newRow.High = ((dr["HIGH"] != DBNull.Value) ? (double)dr["HIGH"] : 0);
					if (c.ColumnName == "OPEN") newRow.Open = ((dr["OPEN"] != DBNull.Value) ? (double)dr["OPEN"] : 0);
					if (c.ColumnName == "CLOSE") newRow.Close = ((dr["CLOSE"] != DBNull.Value) ? (double)dr["CLOSE"] : 0);
					if (c.ColumnName == "VOLUME") newRow.Volume = ((dr["VOLUME"] != DBNull.Value) ? (double)dr["VOLUME"] : 0);

				}
			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdateHistory_Daily(newRow, recId, false, false);
		}

		private void Add_HISTORY(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperHistory();
			try
			{

				foreach (DataColumn c in dr.Table.Columns)
				{
					if (c.ColumnName == "RECID") newRow.RecID = ((dr["RECID"] != DBNull.Value) ? (long)dr["RECID"] : 0);
					if (c.ColumnName == "TIME") newRow.Time = ((dr["TIME"] != DBNull.Value) ? (DateTime)dr["TIME"] : DateTime.MinValue);
					if (c.ColumnName == "TICKER") newRow.Ticker = ((dr["TICKER"] != DBNull.Value) ? (string)dr["TICKER"] : string.Empty);
					if (c.ColumnName == "LOW") newRow.Low = ((dr["LOW"] != DBNull.Value) ? (double)dr["LOW"] : 0);
					if (c.ColumnName == "HIGH") newRow.High = ((dr["HIGH"] != DBNull.Value) ? (double)dr["HIGH"] : 0);
					if (c.ColumnName == "OPEN") newRow.Open = ((dr["OPEN"] != DBNull.Value) ? (double)dr["OPEN"] : 0);
					if (c.ColumnName == "CLOSE") newRow.Close = ((dr["CLOSE"] != DBNull.Value) ? (double)dr["CLOSE"] : 0);
					if (c.ColumnName == "VOLUME") newRow.Volume = ((dr["VOLUME"] != DBNull.Value) ? (double)dr["VOLUME"] : 0);
					if (c.ColumnName == "PERIOD") newRow.Period = ((dr["PERIOD"] != DBNull.Value) ? (int)dr["PERIOD"] : 0);

				}

			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdateHistory(newRow, recId, false, false);
		}

		private void Add_FIRM_HOLDING_TOTAL(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperFirm_Holding_Total();
			try
			{

				foreach (DataColumn c in dr.Table.Columns)
				{

					if (c.ColumnName == "CLIENTID") newRow.ClientID = ((dr["CLIENTID"] != DBNull.Value) ? (int)dr["CLIENTID"] : 0);
					if (c.ColumnName == "TRDACCID") newRow.TrdAccID = ((dr["TRDACCID"] != DBNull.Value) ? (string)dr["TRDACCID"] : string.Empty);
					if (c.ColumnName == "ACCTYPE") newRow.AccType = ((dr["ACCTYPE"] != DBNull.Value) ? (string)dr["ACCTYPE"] : string.Empty);
					if (c.ColumnName == "SECCODE") newRow.SecCode = ((dr["SECCODE"] != DBNull.Value) ? (string)dr["SECCODE"] : string.Empty);
					if (c.ColumnName == "ISSUECODE") newRow.IssueCode = ((dr["ISSUECODE"] != DBNull.Value) ? (string)dr["ISSUECODE"] : string.Empty);
					if (c.ColumnName == "OPENBAL") newRow.OpenBal = ((dr["OPENBAL"] != DBNull.Value) ? (long)dr["OPENBAL"] : 0);
					if (c.ColumnName == "CURRENTPOS") newRow.CurrentPos = ((dr["CURRENTPOS"] != DBNull.Value) ? (long)dr["CURRENTPOS"] : 0);
					if (c.ColumnName == "MIN") newRow.Min = ((dr["MIN"] != DBNull.Value) ? (long)dr["MIN"] : 0);
					if (c.ColumnName == "PLANNEDPOSBUY") newRow.PlannedPosBuy = ((dr["PLANNEDPOSBUY"] != DBNull.Value) ? (long)dr["PLANNEDPOSBUY"] : 0);
					if (c.ColumnName == "PLANNEDPOSSELL") newRow.PlannedPosSell = ((dr["PLANNEDPOSSELL"] != DBNull.Value) ? (long)dr["PLANNEDPOSSELL"] : 0);
					if (c.ColumnName == "TODAYBUY") newRow.TodayBuy = ((dr["TODAYBUY"] != DBNull.Value) ? (long)dr["TODAYBUY"] : 0);
					if (c.ColumnName == "TODAYSELL") newRow.TodaySell = ((dr["TODAYSELL"] != DBNull.Value) ? (long)dr["TODAYSELL"] : 0);
					if (c.ColumnName == "VARMARGIN") newRow.VarMargin = ((dr["VARMARGIN"] != DBNull.Value) ? (double)dr["VARMARGIN"] : 0);
					if (c.ColumnName == "VARMARGINREAL") newRow.VarMarginReal = ((dr["VARMARGINREAL"] != DBNull.Value) ? (double)dr["VARMARGINREAL"] : 0);
					if (c.ColumnName == "VARMARGINOPT") newRow.VarMarginOpt = ((dr["VARMARGINOPT"] != DBNull.Value) ? (double)dr["VARMARGINOPT"] : 0);
					if (c.ColumnName == "FIRMID") newRow.FirmID = ((dr["FIRMID"] != DBNull.Value) ? (string)dr["FIRMID"] : string.Empty);
					if (c.ColumnName == "TICKER") newRow.Ticker = ((dr["TICKER"] != DBNull.Value) ? (string)dr["TICKER"] : string.Empty);

				}

			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdateHoldings(newRow, recId, false, false);
		}

		private void Add_TRDACC(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperTrdAcc();
			try
			{
				foreach (DataColumn c in dr.Table.Columns)
				{

					if (c.ColumnName == "TRDACCID") newRow.TrdAccID = ((dr["TRDACCID"] != DBNull.Value) ? (string)dr["TRDACCID"] : string.Empty);
					if (c.ColumnName == "MAINTRDACCID") newRow.MainTrdAccID = ((dr["MAINTRDACCID"] != DBNull.Value) ? (string)dr["MAINTRDACCID"] : string.Empty);
					if (c.ColumnName == "FIRMID") newRow.FirmID = ((dr["FIRMID"] != DBNull.Value) ? (string)dr["FIRMID"] : string.Empty);
					if (c.ColumnName == "NAME") newRow.Name = ((dr["NAME"] != DBNull.Value) ? (string)dr["NAME"] : string.Empty);
					if (c.ColumnName == "ACCTYPE") newRow.AccType = ((dr["ACCTYPE"] != DBNull.Value) ? (string)dr["ACCTYPE"] : string.Empty);
					if (c.ColumnName == "BANKACCOUNT") newRow.BankAccount = ((dr["BANKACCOUNT"] != DBNull.Value) ? (string)dr["BANKACCOUNT"] : string.Empty);
					if (c.ColumnName == "DEPOACCOUNT") newRow.DepoAccount = ((dr["DEPOACCOUNT"] != DBNull.Value) ? (string)dr["DEPOACCOUNT"] : string.Empty);
					if (c.ColumnName == "BANKCODE") newRow.BankCode = ((dr["BANKCODE"] != DBNull.Value) ? (string)dr["BANKCODE"] : string.Empty);
					if (c.ColumnName == "DEPOCODE") newRow.DepoCode = ((dr["DEPOCODE"] != DBNull.Value) ? (string)dr["DEPOCODE"] : string.Empty);
					if (c.ColumnName == "DESCRIPTION") newRow.Description = ((dr["DESCRIPTION"] != DBNull.Value) ? (string)dr["DESCRIPTION"] : string.Empty);
				}
			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdateTrdacc(newRow, recId, false, false);
		}

		private void Add_TRADES(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperTrades();
			try
			{

				foreach (DataColumn c in dr.Table.Columns)
				{
					if (c.ColumnName == "TRADENO") newRow.TradeNo = ((dr["TRADENO"] != DBNull.Value) ? (long)dr["TRADENO"] : 0);
					if (c.ColumnName == "TRADETIME") newRow.TradeTime = ((dr["TRADETIME"] != DBNull.Value) ? (DateTime)dr["TRADETIME"] : DateTime.MinValue);
					if (c.ColumnName == "ISSUECODE") newRow.IssueCode = ((dr["ISSUECODE"] != DBNull.Value) ? (string)dr["ISSUECODE"] : string.Empty);
					if (c.ColumnName == "REPORATE") newRow.RepoRate = ((dr["REPORATE"] != DBNull.Value) ? (double)dr["REPORATE"] : 0);
					if (c.ColumnName == "REPOTERM") newRow.RepoTerm = ((dr["REPOTERM"] != DBNull.Value) ? (int)dr["REPOTERM"] : 0);
					if (c.ColumnName == "STARTDISCOUNT") newRow.StartDiscount = ((dr["STARTDISCOUNT"] != DBNull.Value) ? (double)dr["STARTDISCOUNT"] : 0);
					if (c.ColumnName == "COMMISSION") newRow.Commission = ((dr["COMMISSION"] != DBNull.Value) ? (double)dr["COMMISSION"] : 0);
					if (c.ColumnName == "TRADETYPE") newRow.TradeType = ((dr["TRADETYPE"] != DBNull.Value) ? (string)dr["TRADETYPE"] : string.Empty);
					if (c.ColumnName == "SETTLECODE") newRow.SettleCode = ((dr["SETTLECODE"] != DBNull.Value) ? (string)dr["SETTLECODE"] : string.Empty);
					if (c.ColumnName == "ORDERNO") newRow.OrderNo = ((dr["ORDERNO"] != DBNull.Value) ? (long)dr["ORDERNO"] : 0);
					if (c.ColumnName == "BUYSELL") newRow.BuySell = ((dr["BUYSELL"] != DBNull.Value) ? (string)dr["BUYSELL"] : string.Empty);
					if (c.ColumnName == "BROKERREF") newRow.BrokerRef = ((dr["BROKERREF"] != DBNull.Value) ? (string)dr["BROKERREF"] : string.Empty);
					if (c.ColumnName == "BROKERID") newRow.BrokerID = ((dr["BROKERID"] != DBNull.Value) ? (string)dr["BROKERID"] : string.Empty);
					if (c.ColumnName == "USERID") newRow.UserID = ((dr["USERID"] != DBNull.Value) ? (string)dr["USERID"] : string.Empty);
					if (c.ColumnName == "FIRMID") newRow.FirmID = ((dr["FIRMID"] != DBNull.Value) ? (string)dr["FIRMID"] : string.Empty);
					if (c.ColumnName == "ACCOUNT") newRow.Account = ((dr["ACCOUNT"] != DBNull.Value) ? (string)dr["ACCOUNT"] : string.Empty);
					if (c.ColumnName == "SECID") newRow.SecID = ((dr["SECID"] != DBNull.Value) ? (int)dr["SECID"] : 0);
					if (c.ColumnName == "SECBOARD") newRow.SecBoard = ((dr["SECBOARD"] != DBNull.Value) ? (string)dr["SECBOARD"] : string.Empty);
					if (c.ColumnName == "SECCODE") newRow.SecCode = ((dr["SECCODE"] != DBNull.Value) ? (string)dr["SECCODE"] : string.Empty);
					if (c.ColumnName == "PRICE") newRow.Price = ((dr["PRICE"] != DBNull.Value) ? (double)dr["PRICE"] : 0);
					if (c.ColumnName == "QUANTITY") newRow.Quantity = ((dr["QUANTITY"] != DBNull.Value) ? (int)dr["QUANTITY"] : 0);
					if (c.ColumnName == "VALUE") newRow.Value = ((dr["VALUE"] != DBNull.Value) ? (double)dr["VALUE"] : 0);
					if (c.ColumnName == "ACCRUEDINT") newRow.AccruedInt = ((dr["ACCRUEDINT"] != DBNull.Value) ? (double)dr["ACCRUEDINT"] : 0);
					if (c.ColumnName == "YIELD") newRow.Yield = ((dr["YIELD"] != DBNull.Value) ? (double)dr["YIELD"] : 0);
					if (c.ColumnName == "PERIOD") newRow.Period = ((dr["PERIOD"] != DBNull.Value) ? (string)dr["PERIOD"] : string.Empty);
					if (c.ColumnName == "EXTREF") newRow.ExtRef = ((dr["EXTREF"] != DBNull.Value) ? (string)dr["EXTREF"] : string.Empty);

				}
			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdateTrades(newRow, recId, false, false);
		}

		private void Add_STOPORDERS(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperStopOrders();
			try
			{

				foreach (DataColumn c in dr.Table.Columns)
				{
					if (c.ColumnName == "STOPTYPE") newRow.StopType = ((dr["STOPTYPE"] != DBNull.Value) ? (string)dr["STOPTYPE"] : string.Empty);
					if (c.ColumnName == "ORDERENDTIME") newRow.OrderEndTime = ((dr["ORDERENDTIME"] != DBNull.Value) ? (DateTime)dr["ORDERENDTIME"] : DateTime.MinValue);
					if (c.ColumnName == "ENDTIME") newRow.EndTime = ((dr["ENDTIME"] != DBNull.Value) ? (DateTime)dr["ENDTIME"] : DateTime.MinValue);
					if (c.ColumnName == "ALERTPRICE") newRow.AlertPrice = ((dr["ALERTPRICE"] != DBNull.Value) ? (double)dr["ALERTPRICE"] : 0);
					if (c.ColumnName == "ORDERNO") newRow.OrderNo = ((dr["ORDERNO"] != DBNull.Value) ? (long)dr["ORDERNO"] : 0);
					if (c.ColumnName == "ORDERTIME") newRow.OrderTime = ((dr["ORDERTIME"] != DBNull.Value) ? (DateTime)dr["ORDERTIME"] : DateTime.MinValue);
					if (c.ColumnName == "WITHDRAWTIME") newRow.WithdrawTime = ((dr["WITHDRAWTIME"] != DBNull.Value) ? (DateTime)dr["WITHDRAWTIME"] : DateTime.MinValue);
					if (c.ColumnName == "STATUS") newRow.Status = ((dr["STATUS"] != DBNull.Value) ? (string)dr["STATUS"] : string.Empty);
					if (c.ColumnName == "MKTLIMIT") newRow.MktLimit = ((dr["MKTLIMIT"] != DBNull.Value) ? (string)dr["MKTLIMIT"] : string.Empty);
					if (c.ColumnName == "BUYSELL") newRow.BuySell = ((dr["BUYSELL"] != DBNull.Value) ? (string)dr["BUYSELL"] : string.Empty);
					if (c.ColumnName == "SPLITFLAG") newRow.SplitFlag = ((dr["SPLITFLAG"] != DBNull.Value) ? (string)dr["SPLITFLAG"] : string.Empty);
					if (c.ColumnName == "IMMCANCEL") newRow.ImmCancel = ((dr["IMMCANCEL"] != DBNull.Value) ? (string)dr["IMMCANCEL"] : string.Empty);
					if (c.ColumnName == "BROKERREF") newRow.BrokerRef = ((dr["BROKERREF"] != DBNull.Value) ? (string)dr["BROKERREF"] : string.Empty);
					if (c.ColumnName == "BROKERID") newRow.BrokerID = ((dr["BROKERID"] != DBNull.Value) ? (string)dr["BROKERID"] : string.Empty);
					if (c.ColumnName == "ACCOUNT") newRow.Account = ((dr["ACCOUNT"] != DBNull.Value) ? (string)dr["ACCOUNT"] : string.Empty);
					if (c.ColumnName == "SECBOARD") newRow.SecBoard = ((dr["SECBOARD"] != DBNull.Value) ? (string)dr["SECBOARD"] : string.Empty);
					if (c.ColumnName == "SECCODE") newRow.SecCode = ((dr["SECCODE"] != DBNull.Value) ? (string)dr["SECCODE"] : string.Empty);
					if (c.ColumnName == "PRICE") newRow.Price = ((dr["PRICE"] != DBNull.Value) ? (double)dr["PRICE"] : 0);
					if (c.ColumnName == "QUANTITY") newRow.Quantity = ((dr["QUANTITY"] != DBNull.Value) ? (int)dr["QUANTITY"] : 0);
					if (c.ColumnName == "ACCRUEDINT") newRow.AccruedInt = ((dr["ACCRUEDINT"] != DBNull.Value) ? (double)dr["ACCRUEDINT"] : 0);
					if (c.ColumnName == "YIELD") newRow.Yield = ((dr["YIELD"] != DBNull.Value) ? (double)dr["YIELD"] : 0);
					if (c.ColumnName == "EXTREF") newRow.ExtRef = ((dr["EXTREF"] != DBNull.Value) ? (string)dr["EXTREF"] : string.Empty);
				}
			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdateStoporders(newRow, recId, false, false);
		}

		private void Add_POSITIONS(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperPositions();
			/*
			 * ClientID, TrdAccID, OpenBal, CurrentPos, PlannedPos, OrderBuy, OrderSell, Netto, Portfolio, Value, 
			 * Commission, Commission2, PlannedCommission, PlannedCommission2, Profit, Free, FreeForShorting, FreeForMargin, FreeForNonMargin, MarginLevel, 
			 * MarginLevelPlanned, FirmID*, CurrCode, Tag, BankAccID, Description, MarginTrading, UseMarginLevel, AccCode, LiquidityRate, 
			 * GuaranteeFactor, PrevLimit, CBPLimit, CBPLUsed, CBPPlanned, Reserved, Surplus, VarMargin, VarMarginOpt, VarMarginReal
			*/
			try
			{
				foreach (DataColumn c in dr.Table.Columns)
				{
					if (c.ColumnName == "CLIENTID") newRow.ClientID = ((dr["CLIENTID"] != DBNull.Value) ? (int)dr["CLIENTID"] : 0);
					if (c.ColumnName == "TRDACCID") newRow.TrdAccID = ((dr["TRDACCID"] != DBNull.Value) ? (string)dr["TRDACCID"] : string.Empty);
					if (c.ColumnName == "OPENBAL") newRow.OpenBal = ((dr["OPENBAL"] != DBNull.Value) ? (double)dr["OPENBAL"] : 0);
					if (c.ColumnName == "CURRENTPOS") newRow.CurrentPos = ((dr["CURRENTPOS"] != DBNull.Value) ? (double)dr["CURRENTPOS"] : 0);
					if (c.ColumnName == "PLANNEDPOS") newRow.PlannedPos = ((dr["PLANNEDPOS"] != DBNull.Value) ? (double)dr["PLANNEDPOS"] : 0);
					if (c.ColumnName == "ORDERBUY") newRow.OrderBuy = ((dr["ORDERBUY"] != DBNull.Value) ? (double)dr["ORDERBUY"] : 0);
					if (c.ColumnName == "ORDERSELL") newRow.OrderSell = ((dr["ORDERSELL"] != DBNull.Value) ? (double)dr["ORDERSELL"] : 0);
					if (c.ColumnName == "NETTO") newRow.Netto = ((dr["NETTO"] != DBNull.Value) ? (double)dr["NETTO"] : 0);
					if (c.ColumnName == "PORTFOLIO") newRow.Portfolio = ((dr["PORTFOLIO"] != DBNull.Value) ? (double)dr["PORTFOLIO"] : 0);
					if (c.ColumnName == "VALUE") newRow.Value = ((dr["VALUE"] != DBNull.Value) ? (double)dr["VALUE"] : 0);
					if (c.ColumnName == "COMMISSION") newRow.Commission = ((dr["COMMISSION"] != DBNull.Value) ? (double)dr["COMMISSION"] : 0);
					if (c.ColumnName == "COMMISSION2") newRow.Commission2 = ((dr["COMMISSION2"] != DBNull.Value) ? (double)dr["COMMISSION2"] : 0);
					if (c.ColumnName == "PLANNEDCOMMISSION") newRow.PlannedCommission = ((dr["PLANNEDCOMMISSION"] != DBNull.Value) ? (double)dr["PLANNEDCOMMISSION"] : 0);
					if (c.ColumnName == "PLANNEDCOMMISSION2") newRow.PlannedCommission2 = ((dr["PLANNEDCOMMISSION2"] != DBNull.Value) ? (double)dr["PLANNEDCOMMISSION2"] : 0);
					if (c.ColumnName == "PROFIT") newRow.Profit = ((dr["PROFIT"] != DBNull.Value) ? (double)dr["PROFIT"] : 0);
					if (c.ColumnName == "FREE") newRow.Free = ((dr["FREE"] != DBNull.Value) ? (double)dr["FREE"] : 0);
					if (c.ColumnName == "FREEFORSHORTING") newRow.FreeForShorting = ((dr["FREEFORSHORTING"] != DBNull.Value) ? (double)dr["FREEFORSHORTING"] : 0);
					if (c.ColumnName == "FREEFORMARGIN") newRow.FreeForMargin = ((dr["FREEFORMARGIN"] != DBNull.Value) ? (double)dr["FREEFORMARGIN"] : 0);
					if (c.ColumnName == "FREEFORNONMARGIN") newRow.FreeForNonMargin = ((dr["FREEFORNONMARGIN"] != DBNull.Value) ? (double)dr["FREEFORNONMARGIN"] : 0);
					if (c.ColumnName == "MARGINLEVEL") newRow.MarginLevel = ((dr["MARGINLEVEL"] != DBNull.Value) ? (double)dr["MARGINLEVEL"] : 0);
					if (c.ColumnName == "MARGINLEVELPLANNED") newRow.MarginLevelPlanned = ((dr["MARGINLEVELPLANNED"] != DBNull.Value) ? (double)dr["MARGINLEVELPLANNED"] : 0);
					if (c.ColumnName == "FIRMID") newRow.FirmID = ((dr["FIRMID"] != DBNull.Value) ? (string)dr["FIRMID"] : string.Empty);
					if (c.ColumnName == "CURRCODE") newRow.CurrCode = ((dr["CURRCODE"] != DBNull.Value) ? (string)dr["CURRCODE"] : string.Empty);
					if (c.ColumnName == "TAG") newRow.Tag = ((dr["TAG"] != DBNull.Value) ? (string)dr["TAG"] : string.Empty);
					if (c.ColumnName == "BANKACCID") newRow.BankAccID = ((dr["BANKACCID"] != DBNull.Value) ? (string)dr["BANKACCID"] : string.Empty);
					if (c.ColumnName == "DESCRIPTION") newRow.Description = ((dr["DESCRIPTION"] != DBNull.Value) ? (string)dr["DESCRIPTION"] : string.Empty);
					if (c.ColumnName == "MARGINTRADING") newRow.MarginTrading = ((dr["MARGINTRADING"] != DBNull.Value) ? (bool)dr["MARGINTRADING"] : false);
					if (c.ColumnName == "USEMARGINLEVEL") newRow.UseMarginLevel = ((dr["USEMARGINLEVEL"] != DBNull.Value) ? (bool)dr["USEMARGINLEVEL"] : false);
					if (c.ColumnName == "ACCCODE") newRow.AccCode = ((dr["ACCCODE"] != DBNull.Value) ? (string)dr["ACCCODE"] : string.Empty);
					if (c.ColumnName == "LIQUIDITYRATE") newRow.LiquidityRate = ((dr["LIQUIDITYRATE"] != DBNull.Value) ? (double)dr["LIQUIDITYRATE"] : 0);
					if (c.ColumnName == "GUARANTEEFACTOR") newRow.GuaranteeFactor = ((dr["GUARANTEEFACTOR"] != DBNull.Value) ? (double)dr["GUARANTEEFACTOR"] : 0);
					if (c.ColumnName == "PREVLIMIT") newRow.PrevLimit = ((dr["PREVLIMIT"] != DBNull.Value) ? (double)dr["PREVLIMIT"] : 0);
					if (c.ColumnName == "CBPLIMIT") newRow.CBPLimit = ((dr["CBPLIMIT"] != DBNull.Value) ? (double)dr["CBPLIMIT"] : 0);
					if (c.ColumnName == "CBPLUSED") newRow.CBPLUsed = ((dr["CBPLUSED"] != DBNull.Value) ? (double)dr["CBPLUSED"] : 0);
					if (c.ColumnName == "CBPPLANNED") newRow.CBPPlanned = ((dr["CBPPLANNED"] != DBNull.Value) ? (double)dr["CBPPLANNED"] : 0);
					if (c.ColumnName == "RESERVED") newRow.Reserved = ((dr["RESERVED"] != DBNull.Value) ? (double)dr["RESERVED"] : 0);
					if (c.ColumnName == "SURPLUS") newRow.Surplus = ((dr["SURPLUS"] != DBNull.Value) ? (double)dr["SURPLUS"] : 0);
					if (c.ColumnName == "VARMARGIN") newRow.VarMargin = ((dr["VARMARGIN"] != DBNull.Value) ? (double)dr["VARMARGIN"] : 0);
					if (c.ColumnName == "VARMARGINOPT") newRow.VarMarginOpt = ((dr["VARMARGINOPT"] != DBNull.Value) ? (double)dr["VARMARGINOPT"] : 0);
					if (c.ColumnName == "VARMARGINREAL") newRow.VarMarginReal = ((dr["VARMARGINREAL"] != DBNull.Value) ? (double)dr["VARMARGINREAL"] : 0);
				}
			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdatePositions(newRow, recId, false, false);
		}


		private void Add_ORDERBOOK(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperOrderbook();
			// SecBoard, SecCode, BuySell, Price, Quantity, 
			try
			{

				foreach (DataColumn c in dr.Table.Columns)
				{
					if (c.ColumnName == "BUYSELL") newRow.BuySell = ((dr["BUYSELL"] != DBNull.Value) ? (string)dr["BUYSELL"] : string.Empty);
					if (c.ColumnName == "SECBOARD") newRow.SecBoard = ((dr["SECBOARD"] != DBNull.Value) ? (string)dr["SECBOARD"] : string.Empty);
					if (c.ColumnName == "SECCODE") newRow.SecCode = ((dr["SECCODE"] != DBNull.Value) ? (string)dr["SECCODE"] : string.Empty);
					if (c.ColumnName == "PRICE") newRow.Price = ((dr["PRICE"] != DBNull.Value) ? (double)dr["PRICE"] : 0);
					if (c.ColumnName == "QUANTITY") newRow.Quantity = ((dr["QUANTITY"] != DBNull.Value) ? (int)dr["QUANTITY"] : 0);

					if (newRow.SecBoard == string.Empty || newRow.SecBoard == null)
					{
						char[] charr = new char[4];
						tableName.CopyTo(10, charr, 0, 4);
						StringBuilder sb = new StringBuilder(4);
						foreach (var item in charr)
						{
							sb.Append(item);
						}
						newRow.SecBoard = sb.ToString();
					}

					if (newRow.SecCode == string.Empty || newRow.SecCode == null)
					{
						char[] charr = new char[9];
						tableName.CopyTo(14, charr, 0, tableName.Length - 14);
						StringBuilder sb = new StringBuilder(9);
						foreach (var item in charr)
						{
							sb.Append(item);
						}
						newRow.SecCode = sb.ToString();
					}

				}
			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdateOrderBook(newRow, recId, false, false);
		}

		private void Add_ORDERS(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperOrders();
			// OrderNo, OrderTime, WithdrawTime, Status, MktLimit, 
			// BuySell, SplitFlag, ImmCancel, EntryType, MarketMaker, 
			// BrokerRef, BrokerID, UserID, FirmID, Account, 
			// SecID, SecBoard, SecCode, Price, Price2, 
			// Quantity, Balance, Value, AccruedInt, EnterType, 
			// Yield, Period, ExtRef, MarketMaker
			try
			{
				foreach (DataColumn c in dr.Table.Columns)
				{
					if (c.ColumnName == "ORDERNO") newRow.OrderNo = ((dr["ORDERNO"] != DBNull.Value) ? (long)dr["ORDERNO"] : 0);
					if (c.ColumnName == "ORDERTIME") newRow.OrderTime = ((dr["ORDERTIME"] != DBNull.Value) ? (DateTime)dr["ORDERTIME"] : DateTime.MinValue);
					if (c.ColumnName == "WITHDRAWTIME") newRow.WithdrawTime = ((dr["WITHDRAWTIME"] != DBNull.Value) ? (DateTime)dr["WITHDRAWTIME"] : DateTime.MinValue);
					if (c.ColumnName == "STATUS") newRow.Status = ((dr["STATUS"] != DBNull.Value) ? (string)dr["STATUS"] : string.Empty);
					if (c.ColumnName == "MKTLIMIT") newRow.MktLimit = ((dr["MKTLIMIT"] != DBNull.Value) ? (string)dr["MKTLIMIT"] : string.Empty);
					if (c.ColumnName == "BUYSELL") newRow.BuySell = ((dr["BUYSELL"] != DBNull.Value) ? (string)dr["BUYSELL"] : string.Empty);
					if (c.ColumnName == "SPLITFLAG") newRow.SplitFlag = ((dr["SPLITFLAG"] != DBNull.Value) ? (string)dr["SPLITFLAG"] : string.Empty);
					if (c.ColumnName == "IMMCANCEL") newRow.ImmCancel = ((dr["IMMCANCEL"] != DBNull.Value) ? (string)dr["IMMCANCEL"] : string.Empty);
					if (c.ColumnName == "ENTRYTYPE") newRow.EntryType = ((dr["ENTRYTYPE"] != DBNull.Value) ? (string)dr["ENTRYTYPE"] : string.Empty);
					if (c.ColumnName == "MARKETMAKER") newRow.MarketMaker = ((dr["MARKETMAKER"] != DBNull.Value) ? (string)dr["MARKETMAKER"] : string.Empty);
					if (c.ColumnName == "BROKERREF") newRow.BrokerRef = ((dr["BROKERREF"] != DBNull.Value) ? (string)dr["BROKERREF"] : string.Empty);
					if (c.ColumnName == "BROKERID") newRow.BrokerID = ((dr["BROKERID"] != DBNull.Value) ? (string)dr["BROKERID"] : string.Empty);
					if (c.ColumnName == "USERID") newRow.UserID = ((dr["USERID"] != DBNull.Value) ? (string)dr["USERID"] : string.Empty);
					if (c.ColumnName == "FIRMID") newRow.FirmID = ((dr["FIRMID"] != DBNull.Value) ? (string)dr["FIRMID"] : string.Empty);
					if (c.ColumnName == "ACCOUNT") newRow.Account = ((dr["ACCOUNT"] != DBNull.Value) ? (string)dr["ACCOUNT"] : string.Empty);
					if (c.ColumnName == "SECID") newRow.SecID = ((dr["SECID"] != DBNull.Value) ? (int)dr["SECID"] : 0);
					if (c.ColumnName == "SECBOARD") newRow.SecBoard = ((dr["SECBOARD"] != DBNull.Value) ? (string)dr["SECBOARD"] : string.Empty);
					if (c.ColumnName == "SECCODE") newRow.SecCode = ((dr["SECCODE"] != DBNull.Value) ? (string)dr["SECCODE"] : string.Empty);
					if (c.ColumnName == "PRICE") newRow.Price = ((dr["PRICE"] != DBNull.Value) ? (double)dr["PRICE"] : 0);
					if (c.ColumnName == "PRICE2") newRow.Price2 = ((dr["PRICE2"] != DBNull.Value) ? (double)dr["PRICE2"] : 0);
					if (c.ColumnName == "QUANTITY") newRow.Quantity = ((dr["QUANTITY"] != DBNull.Value) ? (int)dr["QUANTITY"] : 0);
					if (c.ColumnName == "BALANCE") newRow.Balance = ((dr["BALANCE"] != DBNull.Value) ? (int)dr["BALANCE"] : 0);
					if (c.ColumnName == "VALUE") newRow.Value = ((dr["VALUE"] != DBNull.Value) ? (double)dr["VALUE"] : 0);
					if (c.ColumnName == "ACCRUEDINT") newRow.AccruedInt = ((dr["ACCRUEDINT"] != DBNull.Value) ? (double)dr["ACCRUEDINT"] : 0);
					if (c.ColumnName == "ENTERTYPE") newRow.EnterType = ((dr["ENTERTYPE"] != DBNull.Value) ? (string)dr["ENTERTYPE"] : string.Empty);
					if (c.ColumnName == "YIELD") newRow.Yield = ((dr["YIELD"] != DBNull.Value) ? (double)dr["YIELD"] : 0);
					if (c.ColumnName == "PERIOD") newRow.Period = ((dr["PERIOD"] != DBNull.Value) ? (string)dr["PERIOD"] : string.Empty);
					if (c.ColumnName == "EXTREF") newRow.ExtRef = ((dr["EXTREF"] != DBNull.Value) ? (string)dr["EXTREF"] : string.Empty);
					if (c.ColumnName == "MARKETMAKER") newRow.MarketMaker = ((dr["MARKETMAKER"] != DBNull.Value) ? (string)dr["MARKETMAKER"] : string.Empty);

				}

			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdateOrders(newRow, recId, false, false);
		}

		private void Add_NEWS(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperNews();
			//NewsNo, Time, ContentType, Source, Subject, Body
			try
			{

				foreach (DataColumn c in dr.Table.Columns)
				{

					if (c.ColumnName == "NEWSNO") newRow.NewsNo = ((dr["NEWSNO"] != DBNull.Value) ? (int)dr["NEWSNO"] : 0);
					if (c.ColumnName == "TIME") newRow.Time = ((dr["TIME"] != DBNull.Value) ? (DateTime)dr["TIME"] : DateTime.MinValue);
					if (c.ColumnName == "CONTENTTYPE") newRow.ContentType = ((dr["CONTENTTYPE"] != DBNull.Value) ? (string)dr["CONTENTTYPE"] : string.Empty);
					if (c.ColumnName == "SOURCE") newRow.ContentType = ((dr["SOURCE"] != DBNull.Value) ? (string)dr["SOURCE"] : string.Empty);
					if (c.ColumnName == "SUBJECT") newRow.ContentType = ((dr["SUBJECT"] != DBNull.Value) ? (string)dr["SUBJECT"] : string.Empty);
					if (c.ColumnName == "BODY") newRow.ContentType = ((dr["BODY"] != DBNull.Value) ? (string)dr["BODY"] : string.Empty);

				}
			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdateNews(newRow, recId, false, false);
		}

		private void Add_INDEXES(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperIndexes();
			//"SHORTNAME, NAME, DECIMALS, CURRENTVALUE, HIGH, LOW, INDEXBOARD, INDEXCODE, PREVCLOSE, TIME, USDRATE"
			try
			{
				foreach (DataColumn c in dr.Table.Columns)
				{

					if (c.ColumnName == "SHORTNAME") newRow.ShortName = ((dr["SHORTNAME"] != DBNull.Value) ? (string)dr["SHORTNAME"] : string.Empty);
					if (c.ColumnName == "NAME") newRow.Name = ((dr["NAME"] != DBNull.Value) ? (string)dr["NAME"] : string.Empty);
					if (c.ColumnName == "DECIMALS") newRow.Decimals = ((dr["DECIMALS"] != DBNull.Value) ? (byte)dr["DECIMALS"] : 0);
					if (c.ColumnName == "CURRENTVALUE") newRow.CurrentValue = dr["CURRENTVALUE"] != DBNull.Value ? (double)dr["CURRENTVALUE"] : 0;
					if (c.ColumnName == "HIGH") newRow.High = dr["HIGH"] != DBNull.Value ? (double)dr["HIGH"] : 0;
					if (c.ColumnName == "LOW") newRow.Low = dr["LOW"] != DBNull.Value ? (double)dr["LOW"] : 0;
					if (c.ColumnName == "INDEXBOARD") newRow.IndexBoard = ((dr["INDEXBOARD"] != DBNull.Value) ? (string)dr["INDEXBOARD"] : string.Empty);
					if (c.ColumnName == "INDEXCODE") newRow.IndexCode = ((dr["INDEXCODE"] != DBNull.Value) ? (string)dr["INDEXCODE"] : string.Empty);
					if (c.ColumnName == "PREVCLOSE") newRow.PrevClose = dr["PREVCLOSE"] != DBNull.Value ? (double)dr["PREVCLOSE"] : 0;
					if (c.ColumnName == "TIME") newRow.Time = ((dr["TIME"] != DBNull.Value) ? (DateTime)dr["TIME"] : DateTime.MinValue);
					if (c.ColumnName == "USDRATE") newRow.UsdRate = dr["USDRATE"] != DBNull.Value ? (double)dr["USDRATE"] : 0;

				}
			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdateIndexes(newRow, recId, false, false);
		}

		private void Add_SECURITIES(object state)
		{
			DataRow dr = (DataRow)((TableDataEventArgs)state).DataRow;
			DataTable dt = (DataTable)((TableDataEventArgs)state).DataTable;
			long recId = (long)((TableDataEventArgs)state).RecID;
			string tableName = dt.TableName;

			var newRow = new WrapperSecurities();
			//"SHORTNAME, SECBOARD, SECCODE, SECNAME, DECIMALS, BID, OFFER, LOW, HIGH, PREVPRICE, OPEN, LAST, NUMTRADES, TIME, STEPPRICE, TRADINGSTATUS, TICKER";
			try
			{
				foreach (DataColumn c in dr.Table.Columns)
				{

					if (c.ColumnName == "SHORTNAME") newRow.ShortName = ((dr["SHORTNAME"] != DBNull.Value) ? (string)dr["SHORTNAME"] : string.Empty);
					if (c.ColumnName == "SECBOARD") newRow.SecBoard = (string)((dr["SECBOARD"] != DBNull.Value) ? (string)dr["SECBOARD"] : string.Empty);
					if (c.ColumnName == "SECCODE") newRow.SecCode = (string)((dr["SECCODE"] != DBNull.Value) ? (string)dr["SECCODE"] : string.Empty);
					if (c.ColumnName == "SECNAME") newRow.SecName = (string)((dr["SECNAME"] != DBNull.Value) ? (string)dr["SECNAME"] : string.Empty);
					if (c.ColumnName == "DECIMALS") newRow.Decimals = ((dr["DECIMALS"] != DBNull.Value) ? (byte)dr["DECIMALS"] : 0);
					if (c.ColumnName == "BID") newRow.Bid = ((dr["BID"] != DBNull.Value) ? (double)dr["BID"] : 0);
					if (c.ColumnName == "OFFER") newRow.Offer = ((dr["OFFER"] != DBNull.Value) ? (double)dr["OFFER"] : 0);
					if (c.ColumnName == "LOW") newRow.Low = ((dr["LOW"] != DBNull.Value) ? (double)dr["LOW"] : 0);
					if (c.ColumnName == "HIGH") newRow.High = ((dr["HIGH"] != DBNull.Value) ? (double)dr["HIGH"] : 0);
					if (c.ColumnName == "PREVPRICE") newRow.PrevPrice = ((dr["PREVPRICE"] != DBNull.Value) ? (double)dr["PREVPRICE"] : 0);
					if (c.ColumnName == "OPEN") newRow.Open = ((dr["OPEN"] != DBNull.Value) ? (double)dr["OPEN"] : 0);
					if (c.ColumnName == "LAST") newRow.Last = ((dr["LAST"] != DBNull.Value) ? (double)dr["LAST"] : 0);
					if (c.ColumnName == "NUMTRADES") newRow.NumTrades = ((dr["NUMTRADES"] != DBNull.Value) ? (int)dr["NUMTRADES"] : 0);
					if (c.ColumnName == "TIME") newRow.Time = ((dr["TIME"] != DBNull.Value) ? (DateTime)dr["TIME"] : DateTime.MinValue);
					if (c.ColumnName == "STEPPRICE") newRow.StepPrice = ((dr["STEPPRICE"] != DBNull.Value) ? (double)dr["STEPPRICE"] : 0);
					if (c.ColumnName == "TRADINGSTATUS") newRow.TradingStatus = ((dr["TRADINGSTATUS"] != DBNull.Value) ? (string)dr["TRADINGSTATUS"] : string.Empty);
					if (c.ColumnName == "TICKER") newRow.Ticker = ((dr["TICKER"] != DBNull.Value) ? (string)dr["TICKER"] : string.Empty);

				}
			}
			catch (Exception ex)
			{
				RQS_evhLogLine(null, new TableEventArgs(ex.Message));
			}
			m_SecMaster.UpdateSecurities(newRow, recId, false, false);
		}

		private void ALL_TRADES_AddRowHandler(object sender, TableDataEventArgs e)
		{
			//ThreadPool.QueueUserWorkItem(Add_ALL_TRADES, e);
			Add_ALL_TRADES(e);
		}

		private void TESYSTIME_AddRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Add_TESYSTIME, e);
		}

		private void BOARDS_AddRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Add_BOARDS, e);
		}

		private void HISTORY_DAILY_AddRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Add_HISTORY_DAILY, e);
		}

		private void HISTORY_AddRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Add_HISTORY, e);
		}

		private void FIRM_HOLDING_TOTAL_AddRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Add_FIRM_HOLDING_TOTAL, e);
		}

		private void TRDACC_AddRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Add_TRDACC, e);
		}

		private void TRADES_AddRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Add_TRADES, e);
		}

		private void STOPORDERS_AddRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Add_STOPORDERS, e);
		}

		private void POSITIONS_AddRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Add_POSITIONS, e);
		}

		private void ORDERBOOK_AddRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Add_ORDERBOOK, e);
		}

		private void ORDERS_AddRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Add_ORDERS, e);
		}

		private void NEWS_AddRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Add_NEWS, e);
		}

		private void INDEXES_AddRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Add_INDEXES, e);
		}

		private void SECURITIES_AddRowHandler(object sender, TableDataEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(Add_SECURITIES, e);
		}

		#endregion Добавление данных

				#endregion События_и_методы_по_работе_с_таблицами

		#region Работа_с_заявками

		/// <summary>
		/// Добавление ордера
		/// </summary>
		/// <param name="buySell">Направление операции: "B" – покупка, "S" – продажа.</param>
		/// <param name="mktLimit">Тип заявки: "M" – рыночная, "L" – лимитированная.</param>
		/// <param name="splitFlag">Признак расщепления цены: "S" – по разным ценам, "O" – по одной цене.</param>
		/// <param name="immCancel">Условие исполнения: " " (пробел) – поставить в очередь, "N" – немедленно или отклонить, "W" – снять остаток.</param>
		/// <param name="entryType">Тип ввода значения цены: "P" – цена, "Y" – доходность, "W" – средневзвешенная цена.</param>
		/// <param name="marketMaker">Признак заявки Маркет-Мейкера: " " (пробел) – обычная заявка, "M" – заявка Маркет-Мейкера.</param>
		/// <param name="secBoard">Код режима торгов для финансового инструмента.</param>
		/// <param name="secCode">Код финансового инструмента.</param>
		/// <param name="issueCode">Код выпуска ценной бумаги.</param>
		/// <param name="price">Цена за одну ценную бумагу.</param>
		/// <param name="amount">Количество ценных бумаг, выраженное в лотах.</param>
		/// <param name="extRef">Внешняя ссылка.</param>
		/// <param name="orderNo">Cодержит номер зарегистрированной заявки</param>
		/// <param name="resultMsg">Cодержит текстовое сообщение о результате операции</param>
		public void AddOrder(string buySell, string mktLimit, string splitFlag, string immCancel, string entryType, string marketMaker, string secBoard, string secCode, string issueCode, double price, int amount, string extRef, out long orderNo, out string resultMsg)
		{

			Slot slot = m_TransSlot;

			string account = slot.TrdAccID;
			string brokerRef = slot.BrokerRef;
			DateTime endTime = DateTime.MinValue;

			slot.AddOrder(account, buySell, mktLimit, splitFlag, immCancel, entryType, marketMaker, secBoard, secCode, issueCode, price, amount, brokerRef, extRef, endTime, out orderNo, out resultMsg);
			slot.RefreshAllTables();
			m_OrderDatas.AddData(orderNo, buySell, mktLimit, splitFlag, immCancel, entryType, marketMaker, secBoard, secCode, issueCode, price, amount, extRef);
			RQS_evhLogLine(slot, new TableEventArgs(string.Format("ДОБАВЛЕНИЕ ОРДЕРА: '{0}', номер ордера: {1}", resultMsg, orderNo)));

		}

		/// <summary>
		/// Сдвиг одной или двух ранее введенных заявок по их номерам.
		/// </summary>
		/// <param name="mode">Режим выполнения операции. 0 - Оставить количества в заявках, какие стоят; 1 - Изменить количества в заявках на присланные; 2 - При несовпадении присланных количеств с текущим хотя бы в одной заявке – обе их только снять (и не ставить). </param>
		/// <param name="orderNo1">Номер первой удаляемой заявки.</param>
		/// <param name="price1">Новая цена для первой заявки.</param>
		/// <param name="amount1">Новое количество единиц инструмента для первой заявки.</param>
		/// <param name="extRef1">Новая внешняя ссылка для первой заявки.</param>
		/// <param name="orderNo2">Номер второй удаляемой заявки.</param>
		/// <param name="price2">Новая цена для второй заявки.</param>
		/// <param name="amount2">Новое количество единиц инструмента для второй заявки.</param>
		/// <param name="extRef2">Новая внешняя ссылка для второй заявки.</param>
		/// <param name="newOrderNo1">Номер сдвинутой заявки 1.</param>
		/// <param name="newOrderNo2">Номер сдвинутой заявки 2.</param>
		/// <param name="resultMsg">Содержит текстовое сообщение о результате операции.</param>
		public void MoveOrder(int mode, long orderNo1, double price1, int amount1, string extRef1, long orderNo2, double price2, int amount2, string extRef2, long newOrderNo1, long newOrderNo2, string resultMsg)
		{
			var slot = m_TransSlot;
			if (slot.ServerType == "SPBEX_FUT")
			{
				// ФОРТС
				slot.MoveOrders(mode, orderNo1, price1, amount1, extRef1, orderNo2, price2, amount2, extRef2, out newOrderNo1, out newOrderNo2, out resultMsg);
				RQS_evhLogLine(slot, new TableEventArgs(string.Format("ПЕРЕСТАВЛЕНИЕ ОРДЕРОВ: '{0}', номер ордера: {1}, {2}", resultMsg, newOrderNo1, newOrderNo2)));
			}
			else
			{
				// Мамба чтоли
				// снимаем и ставим обе заявки
				var orderData = m_OrderDatas.GetData(orderNo1);
				if (DelOrder(orderNo1))
					AddOrder(orderData.BuySell, orderData.MktLimit, orderData.SplitFlag, orderData.ImmCancel, orderData.EntryType, orderData.MarketMaker, orderData.SecBoard, orderData.SecCode, orderData.IssueCode, price1, amount1, orderData.ExtRef, out newOrderNo1, out resultMsg);

				orderData = m_OrderDatas.GetData(orderNo2);
				if (DelOrder(orderNo2))
					AddOrder(orderData.BuySell, orderData.MktLimit, orderData.SplitFlag, orderData.ImmCancel, orderData.EntryType, orderData.MarketMaker, orderData.SecBoard, orderData.SecCode, orderData.IssueCode, price2, amount2, orderData.ExtRef, out newOrderNo2, out resultMsg);

			}
		}

		/// <summary>
		/// Удаление ордера
		/// </summary>
		/// <param name="ordNo">Номер удаляемой заявки</param>
		public bool DelOrder(long ordNo)
		{
			if (ordNo == 0)
				return false;
			Slot slot = m_TransSlot;
			string resultMsg;
			slot.DeleteOrder(ordNo, out resultMsg);
			RQS_evhLogLine(slot, new TableEventArgs(string.Format("УДАЛЕНИЕ ОРДЕРА: '{0}', номер ордера: {1}", resultMsg, ordNo)));

			return true;
		}

		#endregion Работа_с_заявками

		#endregion Методы

		#region События_подключения

		/// <summary>
		/// Событие - Соединение установлено
		/// </summary>
		public event EventHandler Connected;

		void OnConnected(EventArgs e)
		{
			EventHandler connected = Connected;
			if (connected != null)
				connected(this, e);
		}

		/// <summary>
		/// Событие - Репликация таблицы завершена
		/// </summary>
		public event EventHandler TableReplied;

		void OnTableReplied(WrapperEventArgs e)
		{
			EventHandler tableReplied = TableReplied;
			if (tableReplied != null)
				tableReplied(this, e);
		}


		#endregion События_подключения

	}
}
